<?php

namespace App\Libraries;

use App\Models\PermissionModel;
use App\Models\RolePermissionModel;
use App\Models\UserCustomPermissionModel;

class PermissionService
{
    /** Resolved permission set, cached for the duration of the request. */
    private static ?array $resolved = null;

    public static function clearCache(): void
    {
        self::$resolved = null;
    }

    /**
     * Returns the full set of permission names granted to the given user.
     * Result is cached in static memory for the duration of the request.
     */
    public static function resolve(int $userId, int $roleId): array
    {
        if (self::$resolved !== null) {
            return self::$resolved;
        }

        $permModel   = new PermissionModel();
        $rpModel     = new RolePermissionModel();
        $ucpModel    = new UserCustomPermissionModel();

        // Role base permissions
        $rolePermIds = $rpModel->where('role_id', $roleId)->findAll();
        $permIds     = array_column($rolePermIds, 'permission_id');
        $rolePerms   = $permIds ? $permModel->whereIn('id', $permIds)->findAll() : [];
        $granted     = array_flip(array_column($rolePerms, 'name'));

        // User-level overrides
        $overrides = $ucpModel->where('user_id', $userId)->findAll();
        foreach ($overrides as $override) {
            $perm = $permModel->find($override['permission_id']);
            if (!$perm) {
                continue;
            }
            if ((int) $override['granted'] === 0) {
                unset($granted[$perm['name']]);
            } else {
                $granted[$perm['name']] = true;
            }
        }

        self::$resolved = array_keys($granted);
        return self::$resolved;
    }

    /** Check if the current user has a specific permission. */
    public static function has(string $permission): bool
    {
        $ctx  = ChurchContext::getInstance();
        $user = $ctx->getUser();

        if (!$user) {
            return false;
        }

        // Platform admins bypass all permission checks
        if ($ctx->isPlatformAdmin()) {
            return true;
        }

        $perms = self::resolve($user['id'], $user['role_id']);
        return in_array($permission, $perms, true);
    }
}
