<?php

namespace App\Synapse\Tools;

use App\Models\Institution\Institution;
use Illuminate\Contracts\JsonSchema\JsonSchema;
use Laravel\Ai\Contracts\Tool;
use Laravel\Ai\Tools\Request;
use Stringable;

class GetInstitutionDetailsTool implements Tool
{
    public function description(): Stringable|string
    {
        return 'Retrieve full details for a specific institution by its database ID, including all contacts, postal address, aliases, DSAR type, and related institutions. Use this after SearchInstitutions to fetch complete contact information for an institution you have identified.';
    }

    public function schema(JsonSchema $schema): array
    {
        return [
            'institution_id' => $schema->integer()
                ->description('The database ID of the institution to retrieve, as returned by search_institutions.')
                ->required(),
        ];
    }

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

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

        $inst = Institution::with([
            'contacts',
            'currentAddress',
            'aliases',
            'dsarType',
            'relatedInstitutions.contacts',
            'relatedInstitutions.currentAddress',
        ])->find($id);

        if (!$inst) {
            return json_encode(['error' => "Institution with ID {$id} not found."]);
        }

        $addr = $inst->currentAddress;
        $address = null;
        if ($addr) {
            $lines = array_filter([
                $addr->line_1, $addr->line_2, $addr->line_3,
                $addr->line_4, $addr->line_5, $addr->line_6,
                $addr->postcode,
            ]);
            $address = implode(', ', $lines) ?: null;
        }

        $related = $inst->relatedInstitutions->map(function (Institution $rel) {
            $relAddr = $rel->currentAddress;
            $relAddress = null;
            if ($relAddr) {
                $lines = array_filter([
                    $relAddr->line_1, $relAddr->line_2, $relAddr->line_3,
                    $relAddr->line_4, $relAddr->line_5, $relAddr->line_6,
                    $relAddr->postcode,
                ]);
                $relAddress = implode(', ', $lines) ?: null;
            }
            return [
                'id'           => $rel->id,
                'display_name' => $rel->display_name,
                'address'      => $relAddress,
                'contacts'     => $rel->contacts->map(fn ($c) => [
                    'name'      => $c->name,
                    'job_title' => $c->job_title,
                    'email'     => $c->email,
                    'telephone' => $c->telephone,
                    'is_primary'=> $c->is_primary,
                ])->values()->all(),
            ];
        })->values()->all();

        return json_encode([
            'id'                  => $inst->id,
            'display_name'        => $inst->display_name,
            'dsar_type'           => $inst->dsarType?->display_name,
            'send_type'           => $inst->send_type,
            'is_prioritised'      => $inst->is_prioritised,
            'stated_sar_backlog'  => $inst->stated_sar_backlog,
            'aliases'             => $inst->aliases->pluck('alias')->values()->all(),
            'address'             => $address,
            'contacts'            => $inst->contacts->map(fn ($c) => [
                'name'       => $c->name,
                'job_title'  => $c->job_title,
                'email'      => $c->email,
                'telephone'  => $c->telephone,
                'mobile'     => $c->mobile,
                'is_primary' => $c->is_primary,
            ])->values()->all(),
            'related_institutions' => $related,
        ]);
    }
}
