<?php

namespace App\Livewire\Roles;

use App\Domain\Identity\Models\Role;
use App\Domain\Shared\Exceptions\DomainException;
use App\Livewire\Concerns\WithSorting;
use Livewire\Attributes\Layout;
use Livewire\Attributes\Title;
use Livewire\Component;

#[Layout('layouts.app')]
#[Title('الأدوار والصلاحيات')]
class RoleList extends Component
{
    use WithSorting;

    public ?int $confirmingDeleteId = null;

    public function mount(): void
    {
        if (!request()->has('sortBy')) {
            $this->sortBy = 'level';
        }
        if (!request()->has('sortDir')) {
            $this->sortDir = 'desc';
        }
    }

    public function confirmDelete(int $roleId): void
    {
        $this->confirmingDeleteId = $roleId;
    }

    public function cancelDelete(): void
    {
        $this->confirmingDeleteId = null;
    }

    public function deleteRole(int $roleId): void
    {
        $this->authorize('roles.delete');

        $role = Role::findOrFail($roleId);
        $actor = auth()->user();

        if ($role->is_system) {
            session()->flash('error', __('لا يمكن حذف دور نظامي'));
            $this->confirmingDeleteId = null;
            return;
        }

        if (!$actor->is_super_admin && $role->level >= ($actor->primaryRole?->level ?? 0)) {
            session()->flash('error', __('لا يمكنك حذف دور بمستوى أعلى من مستواك'));
            $this->confirmingDeleteId = null;
            return;
        }

        $userCount = $role->users()->count();
        if ($userCount > 0) {
            session()->flash('error', __('لا يمكن حذف دور مرتبط بـ :count مستخدم. قم بإعادة تعيين المستخدمين أولاً.', ['count' => $userCount]));
            $this->confirmingDeleteId = null;
            return;
        }

        $role->permissions()->detach();
        $role->delete();

        session()->flash('success', __('تم حذف الدور بنجاح'));
        $this->confirmingDeleteId = null;
    }

    public function render()
    {
        $roles = Role::withCount('users')
            ->orderBy($this->sortBy, $this->sortDir)
            ->get();

        $actor = auth()->user();
        $canEditRole = $roles->mapWithKeys(fn ($r) => [
            $r->id => $actor->is_super_admin || $r->level < ($actor->primaryRole?->level ?? 0)
        ])->toArray();

        return view('livewire.roles.role-list', [
            'roles' => $roles,
            'canEditRole' => $canEditRole,
        ]);
    }
}
