<?php

namespace App\Models;

use CodeIgniter\Model;

class RolePermissionModel extends Model
{
    protected $table         = 'role_permissions';
    protected $primaryKey    = 'id';
    protected $returnType    = 'array';
    protected $useTimestamps = false;

    protected $allowedFields = ['role_id', 'permission_id', 'created_at'];

    public function slugsForRole(int $roleId): array
    {
        $rows = $this->db->table('role_permissions rp')
            ->select('p.slug')
            ->join('permissions p', 'p.id = rp.permission_id')
            ->where('rp.role_id', $roleId)
            ->get()
            ->getResultArray();

        return array_column($rows, 'slug');
    }

    public function roleHasPermission(int $roleId, string $slug): bool
    {
        return $this->db->table('role_permissions rp')
            ->join('permissions p', 'p.id = rp.permission_id')
            ->where('rp.role_id', $roleId)
            ->where('p.slug', $slug)
            ->countAllResults() > 0;
    }

    public function permissionIdsForRole(int $roleId): array
    {
        return array_column(
            $this->where('role_id', $roleId)->findAll(),
            'permission_id'
        );
    }

    /**
     * Replace a role's entire permission set in one transaction.
     */
    public function syncForRole(int $roleId, array $permissionIds): void
    {
        $this->db->transStart();

        $this->where('role_id', $roleId)->delete();

        $rows = [];
        foreach (array_unique(array_map('intval', $permissionIds)) as $pid) {
            $rows[] = [
                'role_id'       => $roleId,
                'permission_id' => $pid,
                'created_at'    => date('Y-m-d H:i:s'),
            ];
        }
        if ($rows) {
            $this->insertBatch($rows);
        }

        $this->db->transComplete();
    }

    public function assignAllPermissionsToRole(int $roleId): void
    {
        $allIds = array_column((new PermissionModel())->findAll(), 'id');
        $this->syncForRole($roleId, $allIds);
    }
}
