<?php

namespace App\Components\Dsar\Tranche;

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

class Item extends Component {
    use AuthorizesRequests;
    public Dsar $dsar;

    protected $rules = [
        'dsar.body' => 'required|string',
    ];
    public $content = '';
    public $emailContent = '';
    public $reference = '';

    public function mount() {
        $this->content = $this->dsar->content;
        $this->emailContent = $this->dsar->email_content ?? '';
        $this->reference = $this->dsar->reference ?? '';
    }

    public function toggleApprove(HistoryService $history) {
        $this->authorize('dsars.batch.send');
        $newStatus = ($this->dsar->status === 'approved') ? 'draft' : 'approved';

        if ($newStatus === 'approved' && empty(trim($this->reference))) {
            $this->reference = $this->dsar->generateReference();
        }

        $this->dsar->content = $this->content;
        $this->dsar->email_content = $this->emailContent ?: null;
        $this->dsar->reference = trim($this->reference) ?: null;
        $this->dsar->status  = $newStatus;
        $this->dsar->save();

        $institution = $this->dsar->institution?->display_name ?? 'Unknown';
        $history->add(
            $this->dsar,
            $newStatus === 'approved'
                ? 'DSAR to "' . $institution . '" approved for sending'
                : 'DSAR to "' . $institution . '" approval revoked',
            ['institution' => $institution]
        );

        $this->dispatch('dsar-updated');
    }

    public function updatedContent() {
        $this->authorize('dsars.create');
        $this->dsar->content = $this->content;
        $this->dsar->save();

        $this->dispatch('toast', message: "Content updated.", type: 'success');
    }

    public function updatedEmailContent() {
        $this->authorize('dsars.create');
        $this->dsar->email_content = $this->emailContent ?: null;
        $this->dsar->save();

        $this->dispatch('toast', message: "Email content updated.", type: 'success');
    }

    public function updatedReference() {
        $this->authorize('dsars.create');
        $this->dsar->reference = trim($this->reference) ?: null;
        $this->dsar->save();

        $this->dispatch('toast', message: 'Reference updated.', type: 'success');
    }

    public function render() {
        return view('components.dsar.tranche.item');
    }
}
