<?php

namespace App\Components\Dsar;

use App\Models\Dsar\Dsar;
use App\Models\Dsar\DsarResponse;
use App\Services\HistoryService;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Livewire\Component;

class ResponseLogger extends Component {
    use AuthorizesRequests;

    public Dsar $dsar;

    public string $type = '';
    public string $notes = '';
    public string $receivedAt = '';
    public string $receiverReference = '';

    protected function rules(): array {
        return [
            'type'              => 'required|in:pushback,partial,full,wrong_recipient,unknown_client',
            'receivedAt'        => 'required|date',
            'notes'             => 'nullable|string|max:2000',
            'receiverReference' => 'nullable|string|max:100',
        ];
    }

    public function logResponse(HistoryService $history): void {
        $this->authorize('dsars.responses.log');
        $this->validate();

        $isFlagged = in_array($this->type, DsarResponse::$flaggedTypes);

        $this->dsar->responses()->create([
            'user_id'     => auth()->id(),
            'type'        => $this->type,
            'notes'       => $this->notes ?: null,
            'received_at' => $this->receivedAt,
            'is_flagged'  => $isFlagged,
        ]);

        if (trim($this->receiverReference)) {
            $this->dsar->update(['receiver_reference' => trim($this->receiverReference)]);
        }

        $client = $this->dsar->claim->client;

        $institution = $this->dsar->institution?->display_name ?? 'Unknown';

        $typeLabels = [
            'pushback'        => 'Pushback',
            'partial'         => 'Partial response',
            'full'            => 'Full response',
            'wrong_recipient' => 'Wrong recipient',
            'unknown_client'  => 'Unknown client',
        ];

        if ($this->type === 'full') {
            $this->dsar->update(['status' => 'completed', 'is_flagged' => false]);
            $context = [
                'dsar_id'     => $this->dsar->id,
                'claim_id'    => $this->dsar->claim_id,
                'institution' => $institution,
                'received_at' => $this->receivedAt,
            ];
            $history->add($this->dsar, 'DSAR from "' . $institution . '" completed — full response received', $context);
            $history->add($client, 'DSAR from "' . $institution . '" completed — full response received', $context);
        } else {
            if ($isFlagged) {
                $this->dsar->update(['is_flagged' => true]);
            }
            $context = [
                'dsar_id'     => $this->dsar->id,
                'claim_id'    => $this->dsar->claim_id,
                'institution' => $institution,
                'received_at' => $this->receivedAt,
                'notes'       => $this->notes,
            ];
            $label = $typeLabels[$this->type] ?? ucfirst($this->type);
            $history->add($this->dsar, 'DSAR response from "' . $institution . '": ' . $label, $context);
            $history->add($client, 'DSAR response from "' . $institution . '": ' . $label, $context);
        }

        $this->reset(['type', 'notes', 'receivedAt', 'receiverReference']);
        $this->dsar->refresh();

        $this->dispatch('toast', message: 'Response logged.', type: 'success');
        $this->dispatch('response-logged');
    }

    public function render() {
        return view('components.dsar.response-logger', [
            'responses' => $this->dsar->responses()->with('user')->latest()->get(),
        ]);
    }
}
