<?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 function mount() {
        $this->content = $this->dsar->content;
        $this->emailContent = $this->dsar->email_content ?? '';
    }

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

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

        $this->dsar->content = $this->content;
        $this->dsar->email_content = $this->emailContent ?: 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 render() {
        return view('components.dsar.tranche.item');
    }
}
