<?php

require_once __DIR__ . '/../../core/permissions.php';

class OpportunityAuthorizationException extends RuntimeException
{
}

class OpportunityAccessService
{
    public static function canManage(array $opportunity, array $user): bool
    {
        $userId = isset($user['id']) ? (int)$user['id'] : 0;
        $role = (string)($user['role'] ?? '');

        if ($userId <= 0) return false;
        if (in_array($role, array('admin', 'administracion'), true)) return true;

        $permissions = $user['permissions'] ?? array();
        if (is_string($permissions)) {
            $permissions = json_decode($permissions, true) ?: array();
        }
        if (in_array('crm.manage_all_opportunities', (array)$permissions, true)) return true;

        $ownerId = isset($opportunity['owner_user_id']) ? (int)$opportunity['owner_user_id'] : 0;
        return $ownerId === 0 || $ownerId === $userId;
    }

    public static function canDelete(array $user): bool
    {
        $role = (string)($user['role'] ?? '');
        if (in_array($role, array('admin', 'administracion'), true)) return true;

        $permissions = $user['permissions'] ?? array();
        if (is_string($permissions)) $permissions = json_decode($permissions, true) ?: array();
        return in_array('crm.delete_opportunities', (array)$permissions, true);
    }

    public static function assertCanManage(array $opportunity, array $user, string $action = 'modificar'): void
    {
        if (!self::canManage($opportunity, $user)) {
            throw new OpportunityAuthorizationException('No tienes permiso para ' . $action . ' una oportunidad asignada a otro responsable.');
        }
    }
}
