<?php

namespace App\Livewire\Modals;

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

class CreateWebhook extends ModalComponent
{
    public string $workspaceUlid = '';

    public int $workspaceId = 0;

    public string $url = '';

    public string $secret = '';

    /** @var array<int, string> */
    public array $selectedEvents = [];

    /** @var array<string, string> */
    public array $availableEvents = [
        'link.clicked' => 'Link clicked',
        'link.created' => 'Link created',
        'link.updated' => 'Link updated',
        'link.deleted' => 'Link deleted',
    ];

    /** @return array<string, string> */
    protected function rules(): array
    {
        return [
            'url' => 'required|url|max:2048',
            'secret' => 'nullable|string|max:255',
            'selectedEvents' => 'required|array|min:1',
            'selectedEvents.*' => 'string|in:'.implode(',', array_keys($this->availableEvents)),
        ];
    }

    public function mount(string $workspaceUlid = ''): void
    {
        if ($workspaceUlid) {
            $workspace = Workspace::where('ulid', $workspaceUlid)->firstOrFail();
            abort_unless(
                $workspace->owner_id === auth()->id() ||
                $workspace->members()->where('user_id', auth()->id())->exists(),
                404
            );
            $this->workspaceUlid = $workspaceUlid;
            $this->workspaceId = $workspace->id;
        }
    }

    public function save(): void
    {
        $this->validate();

        $wsId = $this->workspaceId ?: require_workspace()->id;

        Webhook::create([
            'workspace_id' => $wsId,
            'url' => $this->url,
            'secret' => $this->secret ?: Str::random(32),
            'events' => $this->selectedEvents,
            'is_active' => true,
        ]);

        $this->dispatch('webhookCreated');
        $this->closeModal();
    }

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