<?php

declare(strict_types=1);

namespace ImovelZapAi\Owners\Application\Queries;

use Illuminate\Contracts\Pagination\LengthAwarePaginator;
use ImovelZapAi\Owners\Infrastructure\Persistence\Eloquent\OwnerModel;

final class ListOwnersQuery
{
    /**
     * @param  array{search?: string|null, per_page?: int}  $filters
     */
    public function execute(string $tenantId, array $filters = []): LengthAwarePaginator
    {
        $query = OwnerModel::query()
            ->where('tenant_id', $tenantId)
            ->with(['contacts', 'responsible'])
            ->latest();

        if (! empty($filters['search'])) {
            $search = '%'.$filters['search'].'%';
            $query->where(function ($q) use ($search): void {
                $q->where('name', 'ilike', $search)
                    ->orWhere('document', 'ilike', $search)
                    ->orWhere('trade_name', 'ilike', $search);
            });
        }

        return $query->paginate((int) ($filters['per_page'] ?? 20));
    }
}
