<?php

namespace App\Livewire\Modals;

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

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

    public int $webhookId = 0;

    public string $webhookUrl = '';

    public function mount(int $webhookId): void
    {
        $webhook = Webhook::where('id', $webhookId)->firstOrFail();

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

        $this->workspaceId = $webhook->workspace_id;
        $this->webhookId = $webhookId;
        $this->webhookUrl = $webhook->url;
    }

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

        $this->dispatch('webhookDeleted', webhookId: $this->webhookId);
        $this->closeModal();
    }

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

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

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