<?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
    {
        // Cannot assign role with equal or higher level
        $actorRole = $actor->primaryRole;
        if ($actorRole && $role->level >= $actorRole->level) {
            throw new DomainException(__('لا يمكنك تعيين صلاحية أعلى من صلاحيتك'));
        }

        DB::transaction(function () use ($user, $role, $branchId, $actor) {
            // Set as primary role
            $user->update(['role_id' => $role->id]);

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

    public function syncPermissions(Role $role, array $permissionData): void
    {
        // permissionData: [{permission_id, scope}, ...]
        if ($role->is_system) {
            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);
        });
    }
}
