<?php

namespace App\Livewire\Modals;

use App\Domains\Link\Models\Link;
use App\Domains\Workspace\Models\Workspace;
use App\Livewire\Pages\Links\Index;
use Illuminate\View\View;
use LivewireUI\Modal\ModalComponent;

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

    public string $linkUlid = '';

    public string $linkTitle = '';

    public function mount(string $linkUlid): void
    {
        $link = Link::where('ulid', $linkUlid)->firstOrFail();

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

        $this->workspaceId = $link->workspace_id;
        $this->linkUlid = $linkUlid;
        $this->linkTitle = $link->title ?? $link->slug;
    }

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

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

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

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

    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();
    }
}
