<?php

namespace App\Livewire\Modals;

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

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

    public string $workspaceName = '';

    public string $confirmation = '';

    public function mount(string $workspaceUlid): void
    {
        $workspace = Workspace::where('ulid', $workspaceUlid)
            ->where('owner_id', auth()->id())
            ->firstOrFail();

        $this->workspaceUlid = $workspaceUlid;
        $this->workspaceName = $workspace->name;
    }

    /** @return array<string, string> */
    protected function rules(): array
    {
        return [
            'confirmation' => 'required|in:'.$this->workspaceName,
        ];
    }

    /** @return array<string, string> */
    protected function messages(): array
    {
        return [
            'confirmation.in' => 'Please type the workspace name exactly to confirm.',
        ];
    }

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

        Workspace::where('ulid', $this->workspaceUlid)
            ->where('owner_id', auth()->id())
            ->firstOrFail()
            ->delete();

        $this->dispatch('workspaceDeleted', workspaceUlid: $this->workspaceUlid);
        $this->closeModal();
    }

    public static function closeModalOnClickAway(): bool
    {
        return false;
    }

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