<?php

namespace App\Modules\Platform\Geography\Repositories;

use App\Modules\Platform\Geography\Models\GeoRegion;
use App\Support\GeoTenantScope;
use App\Support\LocalizedName;
use Illuminate\Contracts\Pagination\LengthAwarePaginator;
use Illuminate\Support\Collection;

class GeoRegionRepository
{
    /**
     * @return list<array{value: string, label: string}>
     */
    public function searchForLookup(
        int $tenantId,
        string $query,
        int $limit,
        ?int $countryId,
        ?int $onlyId = null,
    ): array {
        if ($onlyId === null && ($countryId === null || $countryId <= 0)) {
            return [];
        }

        $builder = GeoRegion::query()
            ->where('is_active', true)
            ->orderBy('sort_order')
            ->orderBy('id');

        GeoTenantScope::apply($builder, $tenantId);

        if ($countryId !== null && $countryId > 0) {
            $builder->where('country_id', $countryId);
        }

        if ($onlyId !== null) {
            $builder->whereKey($onlyId);
        } else {
            if ($query !== '') {
                $builder->where(function ($q) use ($query): void {
                    $q->where('name->en', 'like', '%'.$query.'%')
                        ->orWhere('name->ar', 'like', '%'.$query.'%');
                });
            }
            $builder->limit($limit);
        }

        return $this->mapRows($builder->get(['id', 'name']));
    }

    public function paginateForTenant(int $tenantId, ?int $countryId, int $perPage = 25): LengthAwarePaginator
    {
        $builder = GeoRegion::query()
            ->with('country')
            ->withCount('cities')
            ->orderBy('sort_order')
            ->orderBy('id');

        GeoTenantScope::apply($builder, $tenantId);

        if ($countryId !== null && $countryId > 0) {
            $builder->where('country_id', $countryId);
        }

        return $builder->paginate($perPage)->withQueryString();
    }

    /**
     * @param  array<string, mixed>  $data
     */
    public function createTenantRegion(int $tenantId, array $data): GeoRegion
    {
        return GeoRegion::query()->create(array_merge($data, [
            'tenant_id' => $tenantId,
            'is_active' => true,
        ]));
    }

    /**
     * @param  Collection<int, GeoRegion>  $rows
     * @return list<array{value: string, label: string}>
     */
    private function mapRows(Collection $rows): array
    {
        $options = [];
        foreach ($rows as $row) {
            $options[] = [
                'value' => (string) $row->id,
                'label' => LocalizedName::fromModel($row),
            ];
        }

        return $options;
    }
}
