<?php

namespace App\Livewire\Modals;

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

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

    public int $workspaceId = 0;

    public string $hostname = '';

    /** @return array<string, string> */
    protected function rules(): array
    {
        return [
            'hostname' => 'required|string|max:255|regex:/^[a-z0-9]([a-z0-9\-\.]+[a-z0-9])?$/i|unique:domains,hostname',
        ];
    }

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

        $workspace = $this->workspaceId
            ? Workspace::findOrFail($this->workspaceId)
            : require_workspace();

        (new CreateDomain)->handle($workspace, $this->hostname);

        $this->dispatch('domainAdded');
        $this->dispatch('toast', message: 'Domain hinzugefügt', type: 'success');
        $this->closeModal();
    }

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

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