<?php

namespace App\Models;

use CodeIgniter\Model;

class UserRoleModel extends Model
{
    protected $table = 'user_roles';
    protected $primaryKey = null;
    protected $allowedFields = ['user_id', 'role_id'];
    protected $useTimestamps = false;

    public function getRolesForUser(int $userId): array
    {
        return $this->db->table('roles')
            ->select('roles.*')
            ->join('user_roles', 'user_roles.role_id = roles.id')
            ->where('user_roles.user_id', $userId)
            ->get()
            ->getResultArray();
    }

    public function assignRoles(int $userId, array $roleIds): void
    {
        $this->where('user_id', $userId)->delete();

        $data = [];
        foreach ($roleIds as $roleId) {
            $data[] = [
                'user_id' => $userId,
                'role_id' => $roleId,
            ];
        }

        if (! empty($data)) {
            $this->insertBatch($data);
        }
    }
}
