<?php

namespace Database\Seeders;

use App\Models\Claim\CareSetting;
use App\Models\Claim\Claim;
use App\Models\Claim\Status;
use App\Models\Client\Client;
use App\Models\Document\Document;
use App\Models\Document\DocumentType;
use App\Models\Dsar\Dsar;
use App\Models\Dsar\DsarEvidenceItem;
use App\Models\Dsar\DsarTranche;
use App\Models\Institution\Institution;
use App\Models\Solicitor\Solicitor;
use App\Services\Witness\WitnessStatementService;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;

/**
 * Seeds ONE realistic demo client/claim used by the Witness Statement design
 * exercise. All four UI concepts read and write this single record, so they can
 * be compared on identical data. Idempotent — safe to run repeatedly.
 *
 * Runs in console, where the BelongsToSolicitor global scope is off, so every
 * row sets solicitor_id explicitly.
 */
class WitnessStatementDemoSeeder extends Seeder
{
    public function run(): void
    {
        DB::transaction(function () {
            $solicitor = Solicitor::firstOrCreate(
                ['domain' => 'witness-demo'],
                ['name' => 'MMA Legal Limited (Demo)']
            );

            $status = Status::firstOrCreate(['display_name' => 'Statement Drafting']);

            $client = Client::firstOrCreate(
                ['slug' => 'witness-demo-oreilly'],
                [
                    'solicitor_id' => $solicitor->id,
                    'reference' => 'APP296699',
                    'title' => 'Mr',
                    'name_first' => 'Michael',
                    'name_last' => "O'Reilly",
                    'date_of_birth' => '1981-09-28',
                    'email_address' => 'michael.oreilly@example.test',
                    'phone_number' => '+447700900123',
                    'lead_source_id' => null,
                ]
            );

            $client->addresses()->firstOrCreate(
                ['owner_id' => $client->id, 'owner_type' => Client::class, 'line_1' => '1 Campbell Town Drive'],
                [
                    'solicitor_id' => $solicitor->id,
                    'line_2' => 'Kilmarnock',
                    'postcode' => 'KA3 1JS',
                    'is_current' => true,
                ]
            );

            $claim = Claim::firstOrCreate(
                ['client_id' => $client->id],
                [
                    'solicitor_id' => $solicitor->id,
                    'status_id' => $status->id,
                    'redress_type' => 'scottish_redress',
                    'case_number' => 'APP296699',
                ]
            );

            $docType = DocumentType::firstOrCreate(['display_name' => 'Records']);

            // Two care settings, each with a DSAR that returned confirmed findings.
            $settings = [
                [
                    'institution' => 'Kerlaw Care Home',
                    'dates' => '1990–1993',
                    'findings' => [
                        ['page' => 1, 'category' => 'social_care', 'severity' => 'high', 'quote' => 'Michael was placed at Kerlaw following the breakdown of his home placement in 1990.'],
                        ['page' => 3, 'category' => 'abuse', 'severity' => 'high', 'quote' => 'Staff member repeatedly singled the child out for punishment, including isolation in a locked room.'],
                        ['page' => 4, 'category' => 'neglect', 'severity' => 'medium', 'quote' => 'Records note inadequate clothing and missed medical appointments over the winter of 1991.'],
                    ],
                ],
                [
                    'institution' => "Rossie Young People's Trust",
                    'dates' => '1993–1996',
                    'findings' => [
                        ['page' => 2, 'category' => 'violence', 'severity' => 'high', 'quote' => 'Physical restraint was used frequently and, on occasion, left visible marks.'],
                        ['page' => 2, 'category' => 'trauma', 'severity' => 'medium', 'quote' => 'The young person presented as withdrawn and reported recurrent nightmares.'],
                    ],
                ],
            ];

            $tranche = DsarTranche::firstOrCreate(
                ['claim_id' => $claim->id],
                ['solicitor_id' => $solicitor->id, 'status' => 'sent']
            );

            foreach ($settings as $i => $data) {
                $institution = Institution::firstOrCreate(
                    ['solicitor_id' => $solicitor->id, 'display_name' => $data['institution']],
                    ['send_type' => 'post']
                );

                CareSetting::firstOrCreate(
                    ['claim_id' => $claim->id, 'institution_id' => $institution->id],
                    ['solicitor_id' => $solicitor->id, 'dates' => $data['dates']]
                );

                $dsar = Dsar::firstOrCreate(
                    ['claim_id' => $claim->id, 'institution_id' => $institution->id],
                    [
                        'solicitor_id' => $solicitor->id,
                        'tranche_id' => $tranche->id,
                        'status' => 'completed',
                        'content' => 'Demo DSAR content',
                        'reference' => 'DSAR-DEMO-'.($i + 1),
                        'posted_at' => now()->subDays(60),
                        'received_at' => now()->subDays(20),
                    ]
                );

                $document = Document::firstOrCreate(
                    [
                        'solicitor_id' => $solicitor->id,
                        'owner_id' => $dsar->id,
                        'owner_type' => Dsar::class,
                        'file_name' => 'care-record-'.($i + 1).'.pdf',
                    ],
                    [
                        'type_id' => $docType->id,
                        'display_name' => $data['institution'].' – Care Record.pdf',
                        'file_type' => 'pdf',
                        'file_size' => 240000,
                        'evidence_status' => 'completed',
                    ]
                );

                foreach ($data['findings'] as $finding) {
                    DsarEvidenceItem::firstOrCreate(
                        [
                            'solicitor_id' => $solicitor->id,
                            'document_id' => $document->id,
                            'page' => $finding['page'],
                            'quote' => $finding['quote'],
                        ],
                        [
                            'dsar_id' => $dsar->id,
                            'category' => $finding['category'],
                            'severity' => $finding['severity'],
                            'comment' => 'Confirmed during Evidence Review.',
                            'source' => 'ai',
                            'confirmed_at' => now()->subDays(10),
                        ]
                    );
                }
            }

            // Bind the tenant so the service's queries and firstOrCreate resolve
            // to the demo solicitor while we build the workspace.
            app()->instance(Solicitor::class, $solicitor);

            /** @var WitnessStatementService $service */
            $service = app(WitnessStatementService::class);
            $ws = $service->resolve($claim->fresh());

            // Exhibit the two strongest confirmed findings so the exhibits panel
            // is populated on first view.
            $topFindings = $service->confirmedEvidence($ws)
                ->sortByDesc(fn ($i) => $i->severity === 'high' ? 2 : 1)
                ->take(2);

            foreach ($topFindings as $item) {
                $service->addExhibit($ws, [
                    'dsar_evidence_item_id' => $item->id,
                    'document_id' => $item->document_id,
                    'page' => $item->page,
                    'label' => Str::limit($item->quote, 60),
                ]);
            }

            // Leave evidence suggestions PENDING so the "awaiting review" state is
            // visible, and add one manual narrative answer. Required questions are
            // deliberately left blank so validation / readiness states have something
            // to show.
            $service->saveAnswer($ws, 'life_before_care', 'where_grew_up', 'I grew up in Kilmarnock with my mother and two younger siblings.');
        });
    }
}
