<?php

namespace App\Livewire\Modals;

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

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

    public int $memberId = 0;

    public string $memberName = '';

    public string $role = 'editor';

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

    public function mount(int $memberId): void
    {
        $member = WorkspaceMember::where('id', $memberId)->firstOrFail();

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

        $this->workspaceId = $member->workspace_id;
        $this->memberId = $memberId;
        $this->memberName = $member->user->name ?? '';
        $this->role = $member->role;
    }

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

        $member = WorkspaceMember::where('id', $this->memberId)
            ->where('workspace_id', $this->workspaceId)
            ->firstOrFail();

        $member->update(['role' => $this->role]);

        $this->dispatch('memberRoleUpdated', memberId: $this->memberId);
        $this->closeModal();
    }

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

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

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