<?php

namespace App\Livewire\Modals;

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

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

    public int $workspaceId = 0;

    public string $email = '';

    public string $role = 'editor';

    /** @return array<string, string> */
    protected function rules(): array
    {
        return [
            'email' => 'required|email|max:255',
            'role' => 'required|in:admin,editor,viewer',
        ];
    }

    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 invite(): void
    {
        $this->validate();

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

        WorkspaceInvitation::create([
            'workspace_id' => $wsId,
            'email' => strtolower($this->email),
            'role' => $this->role,
            'token' => Str::random(40),
            'invited_by' => auth()->id(),
            'expires_at' => now()->addDays(7),
        ]);

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

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

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