<?php

namespace App\Domain\Identity\Services;

use App\Domain\Identity\Models\Role;
use App\Domain\Shared\Exceptions\DomainException;
use App\Models\User;
use Illuminate\Support\Facades\DB;

class RoleService
{
    public function assignRoleToUser(User $user, Role $role, ?int $branchId, User $actor): void
    {
        $actorRole = $actor->primaryRole;
        if (!$actor->is_super_admin && $actorRole && $role->level >= $actorRole->level) {
            throw new DomainException(__('لا يمكنك تعيين صلاحية أعلى من صلاحيتك'));
        }

        DB::transaction(function () use ($user, $role, $branchId, $actor) {
            $user->update([
                'role_id' => $role->id,
                'is_super_admin' => $role->slug === 'super_admin',
            ]);

            $user->roles()->syncWithoutDetaching([
                $role->id => [
                    'branch_id' => $branchId,
                    'assigned_by' => $actor->id,
                ]
            ]);
        });
    }

    public function syncPermissions(Role $role, array $permissionData, ?User $actor = null): void
    {
        if ($actor && !$actor->is_super_admin && $role->level >= ($actor->primaryRole?->level ?? 0)) {
            throw new DomainException(__('لا يمكنك تعديل صلاحيات دور بمستوى أعلى من مستواك'));
        }

        $sync = [];
        foreach ($permissionData as $item) {
            $sync[$item['permission_id']] = ['scope' => $item['scope']];
        }

        $role->permissions()->sync($sync);
    }

    public function createCustomRole(array $data, User $actor): Role
    {
        return DB::transaction(function () use ($data) {
            $data['is_system'] = false;
            return Role::create($data);
        });
    }
}
