<?php

namespace App\Livewire\Admin;

use App\Models\PlanVersion;
use App\Services\Billing\PlanCatalogue;
use LivewireUI\Modal\ModalComponent;

/**
 * Confirmation for discarding an unpublished plan version.
 *
 * Only a draft can be discarded at all — a published version is what customers
 * are contracted to, and the model refuses to delete one. So this is a small
 * destructive action, and the modal says which one it is rather than leaving
 * "delete" next to a row that might be either.
 */
class ConfirmDeletePlanDraft extends ModalComponent
{
    public string $uuid;

    public int $version;

    public string $plan = '';

    public function mount(string $uuid): void
    {
        // Modals are reachable without the page's guards, so this is the real
        // check, not a convenience one.
        $this->authorize('plans.manage');

        $version = PlanVersion::query()->with('family')->where('uuid', $uuid)->firstOrFail();
        abort_if($version->isPublished(), 403);

        $this->uuid = $uuid;
        $this->version = $version->version;
        $this->plan = $version->family->name;
    }

    public function delete(): void
    {
        $this->authorize('plans.manage');

        $version = PlanVersion::query()->where('uuid', $this->uuid)->first();

        // The catalogue decides, in one conditional statement. Checking here and
        // deleting afterwards would leave a window in which the version is
        // published between the two — and a published version must never go.
        if ($version !== null && ! app(PlanCatalogue::class)->discardDraft($version)) {
            $this->dispatch('notify', message: __('plans.discard_too_late'));
        }

        $this->dispatch('plan-draft-deleted');
        $this->closeModal();
    }

    public function render()
    {
        return view('livewire.admin.confirm-delete-plan-draft');
    }
}
