<?php

namespace App\Components\Dsar;

use App\Models\Dsar\Dsar;
use App\Models\Dsar\DsarResponse;
use App\Services\HistoryService;
use Livewire\Component;

class ResponseLogger extends Component {

    public Dsar $dsar;

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

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

    public function logResponse(HistoryService $history): void {
        $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 ($this->type === 'full') {
            $this->dsar->update(['status' => 'completed', 'is_flagged' => false]);
            $history->add($this->dsar, 'DSAR completed — full response received', [
                'received_at' => $this->receivedAt,
            ]);
        } else {
            if ($isFlagged) {
                $this->dsar->update(['is_flagged' => true]);
            }
            $history->add($this->dsar, 'Response logged: ' . $this->type, [
                'received_at' => $this->receivedAt,
                'notes'       => $this->notes,
            ]);
        }

        $this->reset(['type', 'notes', 'receivedAt']);
        $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(),
        ]);
    }
}
