<?php

namespace App\Services;

use App\Models\Customer;
use Illuminate\Support\Collection;

class CustomerDuplicateDetector
{
    public function find(?string $nin, ?string $phone, ?string $email, ?int $excludeId = null): Collection
    {
        $nin = $this->normalize($nin);
        $phone = $this->normalize($phone);
        $email = $email ? mb_strtolower(trim($email)) : null;

        if (! $nin && ! $phone && ! $email) {
            return collect();
        }

        return Customer::query()
            ->when($excludeId, fn ($q) => $q->whereKeyNot($excludeId))
            ->where(function ($q) use ($nin, $phone, $email): void {
                if ($nin) { $q->orWhere('nin', $nin); }
                if ($phone) { $q->orWhere('phone', $phone); }
                if ($email) { $q->orWhereRaw('LOWER(email) = ?', [$email]); }
            })
            ->limit(10)
            ->get();
    }

    private function normalize(?string $value): ?string
    {
        $value = $value === null ? null : trim($value);
        return $value === '' ? null : $value;
    }
}
