<?php

namespace MintyPHP\Repository\Tenant;

use MintyPHP\DB;

class UserTenantRepository implements UserTenantRepositoryInterface
{
    public function listTenantIdsByUserId(int $userId): array
    {
        $rows = DB::select('select tenant_id from user_tenants where user_id = ?', (string) $userId);
        if (!is_array($rows)) {
            return [];
        }
        $ids = [];
        foreach ($rows as $row) {
            $data = $row['user_tenants'] ?? $row;
            if (is_array($data) && isset($data['tenant_id'])) {
                $ids[] = (int) $data['tenant_id'];
            }
        }
        return array_values(array_unique($ids));
    }

    public function replaceForUser(int $userId, array $tenantIds): bool
    {
        DB::delete('delete from user_tenants where user_id = ?', (string) $userId);
        if (!$tenantIds) {
            return true;
        }

        foreach ($tenantIds as $tenantId) {
            DB::insert(
                'insert into user_tenants (user_id, tenant_id, created) values (?,?,NOW())',
                (string) $userId,
                (string) $tenantId
            );
        }

        return true;
    }

    public function countUsersByTenantIds(array $tenantIds): array
    {
        return $this->countByTenantIds($tenantIds, false);
    }

    public function countActiveUsersByTenantIds(array $tenantIds): array
    {
        return $this->countByTenantIds($tenantIds, true);
    }

    private function countByTenantIds(array $tenantIds, bool $activeOnly): array
    {
        $tenantIds = array_values(array_unique(array_map('intval', $tenantIds)));
        $tenantIds = array_values(array_filter($tenantIds, static fn ($id) => $id > 0));
        if (!$tenantIds) {
            return [];
        }

        $placeholders = implode(',', array_fill(0, count($tenantIds), '?'));
        $joinUsersSql = $activeOnly ? ' join users u on u.id = ut.user_id and u.active = 1' : '';

        $rows = DB::select(
            'select ut.tenant_id, count(distinct ut.user_id) as user_count from user_tenants ut' .
            $joinUsersSql .
            ' where ut.tenant_id in (' . $placeholders . ') group by ut.tenant_id',
            ...array_map('strval', $tenantIds)
        );

        if (!is_array($rows)) {
            return [];
        }

        $result = [];
        foreach ($rows as $row) {
            $tenantId = $this->extractIntField($row, 'tenant_id');
            if ($tenantId <= 0) {
                continue;
            }
            $result[$tenantId] = $this->extractIntField($row, 'user_count');
        }

        return $result;
    }

    private function extractIntField(array $row, string $field): int
    {
        foreach ($row as $value) {
            if (!is_array($value)) {
                continue;
            }
            if (array_key_exists($field, $value)) {
                return (int) $value[$field];
            }
        }
        if (array_key_exists($field, $row)) {
            return (int) $row[$field];
        }
        return 0;
    }
}
