<?php

namespace App\Synapse\Tools;

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.';
    }

    public function schema(JsonSchema $schema): array
    {
        return [
            'institution_id' => $schema
                ->integer()
                ->description('The institution ID from the institution database (obtained via SearchInstitutionsTool).')
                ->required(),
        ];
    }

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

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

        $dsars = Dsar::withoutGlobalScopes()
            ->where('institution_id', $institutionId)
            ->whereNotIn('status', ['draft', 'completed'])
            ->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(),
        ]);
    }
}
