<?php

namespace App\Components\Dsar\Tranche;

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

class View extends Component {
    use AuthorizesRequests;

    public DsarTranche $tranche;

    public $toApprove = [];

    public $listeners = [
        'dsar-updated' => 'dsarUpdated',
    ];

    public function mount(): void {
        $this->authorize('dsars.tranche.view');
    }

    #[\Livewire\Attributes\On('dsar-updated')]
    public function dsarUpdated() {
    }

    public function sendBatch(DsarService $service, HistoryService $history) {
        $this->authorize('dsars.batch.send');

        $approved = $this->tranche->dsars()->where('status', 'approved')->get();

        $approved->each(function($dsar) use ($service, $history) {
            $service->send($dsar);
        });

        $this->tranche->update(['status' => 'sent']);

        return redirect()->route('clients.show', $this->tranche->claim->client);
    }

    public function deleteTranche(HistoryService $history) {
        $this->authorize('dsars.delete');

        if ($this->tranche->status !== 'draft') {
            $this->dispatch('toast', message: 'Only draft tranches can be deleted.', type: 'error');
            return;
        }

        $client = $this->tranche->claim->client;
        $count  = $this->tranche->dsars()->count();

        $this->tranche->dsars()->delete();
        $this->tranche->delete();

        $history->add($client, "Draft DSAR tranche deleted ({$count} DSAR(s) removed).");

        return redirect()->route('clients.show', $client);
    }

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