<?php

namespace App\Livewire\Modals;

use App\Domains\Bio\Models\BioPage;
use App\Domains\Workspace\Models\Workspace;
use App\Livewire\Pages\Bio\Index;
use Illuminate\View\View;
use LivewireUI\Modal\ModalComponent;

class DeleteBioPage extends ModalComponent
{
    public int $workspaceId = 0;

    public string $bioUlid = '';

    public string $bioTitle = '';

    public function mount(string $bioUlid): void
    {
        $bio = BioPage::where('ulid', $bioUlid)->firstOrFail();

        $this->authorizeWorkspace($bio->workspace_id);

        $this->workspaceId = $bio->workspace_id;
        $this->bioUlid = $bioUlid;
        $this->bioTitle = $bio->getTranslation('title', 'en') ?? $bio->slug;
    }

    public function delete(): void
    {
        BioPage::where('ulid', $this->bioUlid)
            ->where('workspace_id', $this->workspaceId)
            ->firstOrFail()
            ->delete();

        $this->dispatch('bio-deleted')->to(Index::class);
        $this->dispatch('toast', message: 'Bio Page gelöscht', type: 'success');
        $this->closeModal();
    }

    public static function modalMaxWidth(): string
    {
        return 'sm';
    }

    public function render(): View
    {
        return view('livewire.modals.delete-bio-page');
    }

    private function authorizeWorkspace(int $workspaceId): void
    {
        Workspace::where('id', $workspaceId)
            ->where(fn ($q) => $q
                ->where('owner_id', auth()->id())
                ->orWhereHas('members', fn ($q) => $q->where('user_id', auth()->id()))
            )->firstOrFail();
    }
}
