<?php

namespace App\Synapse\Tools;

use App\Enum\Dsar\DsarStatus;
use App\Models\Dsar\Dsar;
use Illuminate\Contracts\JsonSchema\JsonSchema;
use Laravel\Ai\Contracts\Tool;
use Laravel\Ai\Tools\Request;
use Stringable;

class SearchDsarByReferenceTool implements Tool
{
    public function description(): Stringable|string
    {
        return 'Search for an open DSAR directly by reference number. Use this when you have identified a reference number in the email — either the firm\'s own reference (quoted back as "Your reference") or a previously recorded institution reference. A direct reference match is more reliable than institution name matching.';
    }

    public function schema(JsonSchema $schema): array
    {
        return [
            'reference' => $schema
                ->string()
                ->description('The reference number to search for (firm\'s DSAR reference or institution\'s reference).')
                ->required(),
        ];
    }

    public function handle(Request $request): Stringable|string
    {
        $reference = trim($request['reference'] ?? '');

        if ($reference === '') {
            return json_encode(['error' => 'reference is required']);
        }

        $dsars = Dsar::withoutGlobalScopes()
            ->where(function ($q) use ($reference) {
                $q->where('reference', 'like', "%{$reference}%")
                  ->orWhere('receiver_reference', 'like', "%{$reference}%");
            })
            ->whereNotIn('status', DsarStatus::excludedFromOpen())
            ->with(['claim.client', 'institution'])
            ->orderBy('posted_at', 'desc')
            ->limit(5)
            ->get();

        if ($dsars->isEmpty()) {
            return json_encode([
                'dsars'   => [],
                'count'   => 0,
                'message' => "No open DSARs found matching reference: {$reference}",
            ]);
        }

        $results = $dsars->map(fn (Dsar $dsar) => [
            'dsar_id'     => $dsar->id,
            'reference'   => $dsar->reference,
            'status'      => $dsar->status,
            'posted_at'   => $dsar->posted_at?->toDateString(),
            'institution' => $dsar->institution?->display_name,
            'client_name' => $dsar->claim?->client
                ? trim($dsar->claim->client->name_first . ' ' . $dsar->claim->client->name_last)
                : null,
        ]);

        return json_encode([
            'dsars' => $results,
            'count' => $results->count(),
        ]);
    }
}
