<?php

namespace App\Livewire\Modals;

use App\Domains\Domain\Models\Domain;
use App\Domains\Workspace\Models\Workspace;
use Illuminate\View\View;
use LivewireUI\Modal\ModalComponent;

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

    public int $domainId = 0;

    public string $hostname = '';

    public function mount(int $domainId): void
    {
        $domain = Domain::where('id', $domainId)->firstOrFail();

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

        $this->workspaceId = $domain->workspace_id;
        $this->domainId = $domainId;
        $this->hostname = $domain->hostname;
    }

    public function delete(): void
    {
        Domain::where('id', $this->domainId)
            ->where('workspace_id', $this->workspaceId)
            ->firstOrFail()
            ->delete();

        $this->dispatch('domainDeleted', domainId: $this->domainId);
        $this->dispatch('toast', message: 'Domain gelöscht', type: 'success');
        $this->closeModal();
    }

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

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

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