<?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) {
        $oldStatus = $this->dsar->status;
        $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';
        $event = $newStatus === 'approved'
            ? 'DSAR to "' . $institution . '" approved for sending'
            : 'DSAR to "' . $institution . '" approval revoked';
        $context = [
            'dsar_id'     => $this->dsar->id,
            'claim_id'    => $this->dsar->claim_id,
            'institution' => $institution,
            'from_status' => $oldStatus,
            'to_status'   => $newStatus,
        ];

        $history->add($this->dsar, $event, $context);
        if ($claim = $this->dsar->claim) {
            $history->addForClaim($claim, $event, $context);
        }

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

    public function updatedContent(HistoryService $history) {
        $this->dsar->content = $this->content;
        $this->dsar->save();

        $institution = $this->dsar->institution?->display_name ?? 'Unknown';
        $history->add($this->dsar, 'DSAR letter content edited for "' . $institution . '"', [
            'dsar_id'     => $this->dsar->id,
            'claim_id'    => $this->dsar->claim_id,
            'institution' => $institution,
        ]);

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

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