<?php

namespace App\Components\Dsar\Tranche;

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

class Item extends Component {
    public Dsar $dsar;

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

    public function mount() {
        $this->content = $this->dsar->content;
    }

    public function toggleApprove(HistoryService $history) {
        $newStatus = ($this->dsar->status === 'approved') ? 'draft' : 'approved';
        $this->dsar->content = $this->content;
        $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->dsar->content = $this->content;
        $this->dsar->save();

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

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