-- name: CreateNumericEntitlementUsage :one
INSERT INTO entitlements.numeric_entitlement_usage (entitlement_id, pool_id, resource_key)
VALUES ($1, $2, $3)
RETURNING *;

-- name: GetUsageByPoolAndResource :one
SELECT * FROM entitlements.numeric_entitlement_usage
WHERE pool_id = $1 AND resource_key = $2;

-- name: AtomicIncrementUsage :execresult
UPDATE entitlements.numeric_entitlement_usage neu
SET current_usage = neu.current_usage + 1
WHERE neu.pool_id IN (
    SELECT pa.pool_id FROM entitlements.pool_assignments pa
    WHERE pa.workspace_id = $1 AND pa.is_primary = TRUE AND pa.status = 'active'
)
AND neu.resource_key = $2
AND neu.current_usage < (
    SELECT ne.resource_limit FROM entitlements.numeric_entitlements ne
    WHERE ne.entitlement_id = neu.entitlement_id
);

-- name: AtomicDecrementUsage :execresult
UPDATE entitlements.numeric_entitlement_usage neu
SET current_usage = GREATEST(neu.current_usage - 1, 0)
WHERE neu.pool_id IN (
    SELECT pa.pool_id FROM entitlements.pool_assignments pa
    WHERE pa.workspace_id = $1 AND pa.is_primary = TRUE AND pa.status = 'active'
)
AND neu.resource_key = $2;

-- name: ListNumericEntitlementUsageByPoolID :many
SELECT * FROM entitlements.numeric_entitlement_usage
WHERE pool_id = $1
ORDER BY resource_key ASC;
