<?php

namespace App\Modules\Settings\Rbac\Repositories;

use App\Models\User;
use App\Modules\Settings\Rbac\Models\Role;
use Illuminate\Support\Facades\DB;

class UserRoleRepository
{
    /**
     * @param  list<int>  $roleIds
     */
    public function syncRolesForUser(User $user, int $tenantId, array $roleIds): void
    {
        $valid = Role::query()
            ->where('tenant_id', $tenantId)
            ->where('is_active', true)
            ->whereIn('id', $roleIds)
            ->pluck('id')
            ->all();
        DB::table('user_roles')->where('user_id', $user->id)->delete();
        $now = now();
        $rows = [];
        foreach ($valid as $rid) {
            $rows[] = [
                'user_id' => $user->id,
                'role_id' => $rid,
                'created_at' => $now,
                'updated_at' => $now,
            ];
        }
        if ($rows !== []) {
            DB::table('user_roles')->insert($rows);
        }
    }

    /**
     * @return list<int>
     */
    public function roleIdsForUser(User $user): array
    {
        return DB::table('user_roles')
            ->where('user_id', $user->id)
            ->pluck('role_id')
            ->all();
    }
}
