<?php

namespace MintyPHP\Repository\Tenant;

use MintyPHP\DB;
use MintyPHP\Domain\Taxonomy\TenantStatus;
use MintyPHP\Repository\Support\RepoQuery;
use MintyPHP\Repository\Support\RepositoryArrayHelper;

class TenantRepository implements TenantRepositoryInterface
{
    public function list(): array
    {
        $rows = DB::select(
            'select id, uuid, description, address, postal_code, city, country, region, vat_id, tax_number, phone, fax, email, support_email, support_phone, billing_email, website, privacy_url, imprint_url, primary_color, default_theme, allow_user_theme, status, status_changed_at, status_changed_by, created_by, modified_by, created, modified from tenants order by id desc'
        );
        return RepositoryArrayHelper::unwrapList($rows, 'tenants');
    }

    public function listIds(): array
    {
        $rows = DB::select('select id from tenants');

        return RepositoryArrayHelper::extractIds($rows, 'tenants');
    }

    public function listByIds(array $tenantIds): array
    {
        $tenantIds = RepositoryArrayHelper::sanitizePositiveIds($tenantIds);
        if (!$tenantIds) {
            return [];
        }

        $placeholders = implode(',', array_fill(0, count($tenantIds), '?'));
        $rows = DB::select(
            'select id, uuid, description, address, postal_code, city, country, region, vat_id, tax_number, phone, fax, email, support_email, support_phone, billing_email, website, privacy_url, imprint_url, primary_color, default_theme, allow_user_theme, status, status_changed_at, status_changed_by, created_by, modified_by, created, modified from tenants where id in (' . $placeholders . ')',
            ...array_map('strval', $tenantIds)
        );
        return RepositoryArrayHelper::unwrapList($rows, 'tenants');
    }

    public function listActiveIdsByIds(array $tenantIds): array
    {
        $tenantIds = RepositoryArrayHelper::sanitizePositiveIds($tenantIds);
        if (!$tenantIds) {
            return [];
        }
        $placeholders = implode(',', array_fill(0, count($tenantIds), '?'));
        $params = array_map('strval', $tenantIds);
        $rows = call_user_func_array(
            ['MintyPHP\\DB', 'select'],
            array_merge(
                ["select id from tenants where status = ? and id in ($placeholders)", TenantStatus::Active->value],
                $params
            )
        );
        return RepositoryArrayHelper::extractIds($rows, 'tenants');
    }

    public function listPaged(array $options): array
    {
        $search = trim((string) ($options['search'] ?? ''));
        $status = TenantStatus::tryNormalize((string) ($options['status'] ?? ''));
        $allowedOrder = ['id', 'uuid', 'description', 'status', 'created', 'modified'];
        [$limit, $offset] = RepoQuery::sanitizeLimitOffset($options);
        [$order, $dir] = RepoQuery::sanitizeOrder($options, $allowedOrder);

        $where = [];
        $params = [];
        RepoQuery::addLikeFilter($where, $params, ['description', 'uuid'], $search);
        if ($status !== null) {
            $where[] = 'tenants.status = ?';
            $params[] = $status->value;
        }
        if (!empty($options['tenantUserId'])) {
            $tenantUserId = (int) $options['tenantUserId'];
            if ($tenantUserId > 0) {
                $where[] = 'exists (select 1 from user_tenants ut where ut.user_id = ? and ut.tenant_id = tenants.id)';
                $params[] = (string) $tenantUserId;
            }
        }
        if (array_key_exists('tenantIds', $options)) {
            $tenantIds = $options['tenantIds'];
            $tenantIds = is_array($tenantIds) ? array_values(array_unique(array_map('intval', $tenantIds))) : [];
            $tenantIds = array_values(array_filter($tenantIds, static fn ($id) => $id > 0));
            if ($tenantIds) {
                $where[] = 'tenants.id in (???)';
                $params[] = $tenantIds;
            } else {
                $where[] = '1=0';
            }
        }

        $whereSql = $where ? (' where ' . implode(' and ', $where)) : '';
        $count = DB::selectValue('select count(*) from tenants' . $whereSql, ...$params);
        $total = $count ? (int) $count : 0;

        $query = 'select id, uuid, description, address, postal_code, city, country, region, vat_id, tax_number, phone, fax, email, support_email, support_phone, billing_email, website, privacy_url, imprint_url, primary_color, default_theme, allow_user_theme, status, status_changed_at, status_changed_by, created_by, modified_by, created, modified from tenants' .
            $whereSql .
            sprintf(' order by `%s` %s limit ? offset ?', $order, $dir);

        $queryParams = array_merge($params, [(string) $limit, (string) $offset]);
        $rows = call_user_func_array(['MintyPHP\\DB', 'select'], array_merge([$query], $queryParams));

        return [
            'total' => $total,
            'rows' => RepositoryArrayHelper::unwrapList($rows, 'tenants'),
        ];
    }

    public function find(int $id): ?array
    {
        $row = DB::selectOne(
            'select id, uuid, description, address, postal_code, city, country, region, vat_id, tax_number, phone, fax, email, support_email, support_phone, billing_email, website, privacy_url, imprint_url, primary_color, default_theme, allow_user_theme, status, status_changed_at, status_changed_by, created_by, modified_by, created, modified from tenants where id = ? limit 1',
            (string) $id
        );
        return RepositoryArrayHelper::unwrap($row, 'tenants');
    }

    public function findByUuid(string $uuid): ?array
    {
        $row = DB::selectOne(
            'select id, uuid, description, address, postal_code, city, country, region, vat_id, tax_number, phone, fax, email, support_email, support_phone, billing_email, website, privacy_url, imprint_url, primary_color, default_theme, allow_user_theme, status, status_changed_at, status_changed_by, created_by, modified_by, created, modified from tenants where uuid = ? limit 1',
            $uuid
        );
        return RepositoryArrayHelper::unwrap($row, 'tenants');
    }

    public function create(array $data): mixed
    {
        return DB::insert(
            'insert into tenants (uuid, description, address, postal_code, city, country, region, vat_id, tax_number, phone, fax, email, support_email, support_phone, billing_email, website, privacy_url, imprint_url, primary_color, default_theme, allow_user_theme, status, status_changed_at, status_changed_by, created_by, created) values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,NOW())',
            $data['uuid'] ?? RepoQuery::uuidV4(),
            $data['description'],
            $data['address'] ?? null,
            $data['postal_code'] ?? null,
            $data['city'] ?? null,
            $data['country'] ?? null,
            $data['region'] ?? null,
            $data['vat_id'] ?? null,
            $data['tax_number'] ?? null,
            $data['phone'] ?? null,
            $data['fax'] ?? null,
            $data['email'] ?? null,
            $data['support_email'] ?? null,
            $data['support_phone'] ?? null,
            $data['billing_email'] ?? null,
            $data['website'] ?? null,
            $data['privacy_url'] ?? null,
            $data['imprint_url'] ?? null,
            $data['primary_color'] ?? null,
            $data['default_theme'] ?? null,
            $data['allow_user_theme'] ?? null,
            $data['status'] ?? TenantStatus::Active->value,
            $data['status_changed_at'] ?? null,
            $data['status_changed_by'] ?? null,
            $data['created_by'] ?? null
        );
    }

    public function update(int $id, array $data): bool
    {
        $fields = [
            'description' => $data['description'],
            'address' => $data['address'] ?? null,
            'postal_code' => $data['postal_code'] ?? null,
            'city' => $data['city'] ?? null,
            'country' => $data['country'] ?? null,
            'region' => $data['region'] ?? null,
            'vat_id' => $data['vat_id'] ?? null,
            'tax_number' => $data['tax_number'] ?? null,
            'phone' => $data['phone'] ?? null,
            'fax' => $data['fax'] ?? null,
            'email' => $data['email'] ?? null,
            'support_email' => $data['support_email'] ?? null,
            'support_phone' => $data['support_phone'] ?? null,
            'billing_email' => $data['billing_email'] ?? null,
            'website' => $data['website'] ?? null,
            'privacy_url' => $data['privacy_url'] ?? null,
            'imprint_url' => $data['imprint_url'] ?? null,
            'primary_color' => $data['primary_color'] ?? null,
            'default_theme' => $data['default_theme'] ?? null,
            'allow_user_theme' => $data['allow_user_theme'] ?? null,
            'status' => $data['status'] ?? TenantStatus::Active->value,
        ];
        if (array_key_exists('modified_by', $data)) {
            $fields['modified_by'] = $data['modified_by'];
        }
        if (array_key_exists('status_changed_at', $data)) {
            $fields['status_changed_at'] = $data['status_changed_at'];
        }
        if (array_key_exists('status_changed_by', $data)) {
            $fields['status_changed_by'] = $data['status_changed_by'];
        }

        $setParts = [];
        $params = [];
        foreach ($fields as $field => $value) {
            $setParts[] = sprintf('`%s` = ?', $field);
            $params[] = $value;
        }
        $params[] = (string) $id;

        $query = 'update tenants set ' . implode(', ', $setParts) . ' where id = ?';
        $result = DB::update($query, ...$params);
        return $result !== false;
    }

    public function delete(int $id): bool
    {
        $result = DB::delete('delete from tenants where id = ?', (string) $id);
        return $result !== false;
    }
}
