<?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 SearchOpenDsarsTool implements Tool
{
    public function description(): Stringable|string
    {
        return 'Search for open (not completed or draft) Data Subject Access Requests linked to a specific institution. '
             . 'Returns all outstanding DSARs for that institution with their reference numbers, client details, '
             . 'current status, and expected response dates. Use this after identifying an institution to find '
             . 'which DSAR an inbound email is likely responding to. '
             . 'Optionally pass client_name to narrow results to a specific data subject (full name preferred).';
    }

    public function schema(JsonSchema $schema): array
    {
        return [
            'institution_id' => $schema
                ->integer()
                ->description('The institution ID from the institution database (obtained via SearchInstitutionsTool).')
                ->required(),
            'client_name' => $schema
                ->string()
                ->nullable()
                ->description('Optional: the data subject\'s full name (or partial name) to narrow results. Only use when a full name is clearly identified in the email — not from salutations.')
                ->required(),
        ];
    }

    public function handle(Request $request): Stringable|string
    {
        $institutionId = (int) ($request['institution_id'] ?? 0);
        $clientName    = trim($request['client_name'] ?? '');

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

        $dsars = Dsar::withoutGlobalScopes()
            ->where('institution_id', $institutionId)
            ->whereNotIn('status', DsarStatus::excludedFromOpen())
            ->when($clientName !== '', fn ($q) =>
                $q->whereHas('claim.client', fn ($cq) =>
                    $cq->whereRaw("CONCAT(name_first, ' ', name_last) LIKE ?", ["%{$clientName}%"])
                )
            )
            ->with(['claim.client'])
            ->orderBy('posted_at', 'desc')
            ->get();

        if ($dsars->isEmpty()) {
            return json_encode([
                'dsars' => [],
                'count' => 0,
                'message' => 'No open DSARs found for institution ID ' . $institutionId,
            ]);
        }

        $results = $dsars->map(fn (Dsar $dsar) => [
            'dsar_id'     => $dsar->id,
            'status'      => $dsar->status,
            'posted_at'   => $dsar->posted_at?->toDateString(),
            'expected_at' => $dsar->expected_at?->toDateString(),
            'claim_id'    => $dsar->claim_id,
            '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(),
        ]);
    }
}
