<?php

declare(strict_types=1);

namespace App\Modules\Parties\Application\Services;

use App\Shared\Schema\PartySchemaSupport;
use PDO;

final class PartyLookupService
{
    public function __construct(private PDO $pdo)
    {
    }

    public function ensureSchema(): void
    {
        PartySchemaSupport::ensurePartiesSchema($this->pdo);
    }

    public function search(string $type, string $query): array
    {
        $type = in_array($type, ['all', 'customer', 'supplier'], true) ? $type : 'all';
        $query = trim($query);
        if ($query === '') {
            return [];
        }

        $like = '%' . $query . '%';
        $where = ['is_active=1', '(name LIKE ? OR phone LIKE ? OR phone2 LIKE ? OR code LIKE ?)'];
        $params = [$like, $like, $like, $like];
        if ($type === 'customer') {
            $where[] = 'is_customer=1';
        }
        if ($type === 'supplier') {
            $where[] = 'is_supplier=1';
        }

        $sql = "SELECT id, COALESCE(code, CONCAT('P',LPAD(id,5,'0'))) code, name, phone, is_customer, is_supplier
                FROM parties
                WHERE " . implode(' AND ', $where) . "
                ORDER BY name
                LIMIT 20";
        $statement = $this->pdo->prepare($sql);
        $statement->execute($params);
        return $statement->fetchAll() ?: [];
    }
}
