<?php

namespace MintyPHP\Repository\Access;

use MintyPHP\DB;

class RolePermissionRepository implements RolePermissionRepositoryInterface
{
    public function listPermissionIdsByRoleId(int $roleId): array
    {
        $rows = DB::select('select permission_id from role_permissions where role_id = ?', (string) $roleId);
        if (!is_array($rows)) {
            return [];
        }
        $ids = [];
        foreach ($rows as $row) {
            $data = $row['role_permissions'] ?? $row;
            if (is_array($data) && isset($data['permission_id'])) {
                $ids[] = (int) $data['permission_id'];
            }
        }
        return array_values(array_unique($ids));
    }

    public function countPermissionsByRoleIds(array $roleIds): array
    {
        $roleIds = array_values(array_unique(array_map('intval', $roleIds)));
        $roleIds = array_values(array_filter($roleIds, static fn ($id) => $id > 0));
        if (!$roleIds) {
            return [];
        }

        $placeholders = implode(',', array_fill(0, count($roleIds), '?'));
        $rows = DB::select(
            'select rp.role_id, count(distinct rp.permission_id) as permission_count from role_permissions rp where rp.role_id in (' .
            $placeholders .
            ') group by rp.role_id',
            ...array_map('strval', $roleIds)
        );

        if (!is_array($rows)) {
            return [];
        }

        $result = [];
        foreach ($rows as $row) {
            $roleId = self::extractIntField($row, 'role_id');
            if ($roleId <= 0) {
                continue;
            }
            $result[$roleId] = self::extractIntField($row, 'permission_count');
        }

        return $result;
    }

    public function replaceForRole(int $roleId, array $permissionIds): bool
    {
        DB::delete('delete from role_permissions where role_id = ?', (string) $roleId);
        $ids = array_values(array_unique(array_filter(array_map('intval', $permissionIds))));
        if (!$ids) {
            return true;
        }
        foreach ($ids as $permissionId) {
            DB::insert(
                'insert into role_permissions (role_id, permission_id, created) values (?,?,NOW())',
                (string) $roleId,
                (string) $permissionId
            );
        }
        return true;
    }

    public function listRoleIdsByPermissionId(int $permissionId): array
    {
        $rows = DB::select('select role_id from role_permissions where permission_id = ?', (string) $permissionId);
        if (!is_array($rows)) {
            return [];
        }
        $ids = [];
        foreach ($rows as $row) {
            $data = $row['role_permissions'] ?? $row;
            if (is_array($data) && isset($data['role_id'])) {
                $ids[] = (int) $data['role_id'];
            }
        }
        return array_values(array_unique($ids));
    }

    public function replaceForPermission(int $permissionId, array $roleIds): bool
    {
        DB::delete('delete from role_permissions where permission_id = ?', (string) $permissionId);
        $ids = array_values(array_unique(array_filter(array_map('intval', $roleIds))));
        if (!$ids) {
            return true;
        }
        foreach ($ids as $roleId) {
            DB::insert(
                'insert into role_permissions (role_id, permission_id, created) values (?,?,NOW())',
                (string) $roleId,
                (string) $permissionId
            );
        }
        return true;
    }

    public function listPermissionKeysByRoleIds(array $roleIds): array
    {
        $ids = array_values(array_unique(array_filter(array_map('intval', $roleIds))));
        if (!$ids) {
            return [];
        }
        $rows = DB::select(
            'select p.`key` as `key` from role_permissions rp ' .
            'join roles r on r.id = rp.role_id and r.active = 1 ' .
            'join permissions p on p.id = rp.permission_id and p.active = 1 ' .
            'where rp.role_id in (???)',
            array_map('strval', $ids)
        );
        if (!is_array($rows)) {
            return [];
        }
        $keys = [];
        foreach ($rows as $row) {
            $data = $row['p'] ?? $row;
            if (is_array($data) && isset($data['key'])) {
                $keys[] = (string) $data['key'];
            } elseif (is_array($row) && isset($row['key'])) {
                $keys[] = (string) $row['key'];
            }
        }
        return array_values(array_unique($keys));
    }

    public function listPermissionsWithRolesByRoleIds(array $roleIds): array
    {
        $ids = array_values(array_unique(array_filter(array_map('intval', $roleIds))));
        if (!$ids) {
            return [];
        }
        $rows = DB::select(
            'select rp.permission_id as permission_id, p.`key` as `key`, p.description as `description`, r.description as role ' .
            'from role_permissions rp join permissions p on p.id = rp.permission_id and p.active = 1 ' .
            'join roles r on r.id = rp.role_id and r.active = 1 where rp.role_id in (???) ' .
            'order by p.`key` asc, r.description asc',
            array_map('strval', $ids)
        );
        if (!is_array($rows)) {
            return [];
        }
        $permMap = [];
        foreach ($rows as $row) {
            $rowPerm = $row['p'] ?? ($row['permissions'] ?? $row);
            $rowRole = $row['r'] ?? ($row['roles'] ?? $row);
            $rowRp = $row['rp'] ?? ($row['role_permissions'] ?? $row);

            $permId = $rowRp['permission_id'] ?? ($row['permission_id'] ?? null);
            $key = (string) ($rowPerm['key'] ?? $row['key'] ?? '');
            if ($permId === null || $key === '') {
                continue;
            }
            if (!isset($permMap[$permId])) {
                $desc = (string) ($rowPerm['description'] ?? $row['description'] ?? '');
                $permMap[$permId] = [
                    'key' => $key,
                    'description' => $desc,
                    'roles' => [],
                ];
            }
            $roleLabel = (string) ($rowRole['description'] ?? $rowRole['role'] ?? $row['role'] ?? '');
            if ($roleLabel !== '') {
                $permMap[$permId]['roles'][] = $roleLabel;
            }
        }
        foreach ($permMap as &$item) {
            $item['roles'] = array_values(array_unique($item['roles']));
        }
        unset($item);
        return array_values($permMap);
    }

    private function extractIntField(array $row, string $field): int
    {
        foreach ($row as $value) {
            if (!is_array($value)) {
                continue;
            }
            if (array_key_exists($field, $value)) {
                return (int) $value[$field];
            }
        }
        if (array_key_exists($field, $row)) {
            return (int) $row[$field];
        }
        return 0;
    }
}
