-- name: GetCurrentBalance :one
SELECT COALESCE(
    (SELECT balance_after FROM tenant_quota_ledgers
     WHERE tenant_id = sqlc.arg(tenant_id) AND quota_type = sqlc.arg(quota_type)
     ORDER BY created_at DESC LIMIT 1), 0
)::INT AS balance;

-- name: InsertQuotaLedger :one
INSERT INTO tenant_quota_ledgers (tenant_id, operator_id, quota_type, delta, balance_after, reason, reference_type, reference_id)
VALUES (sqlc.arg(tenant_id), sqlc.arg(operator_id), sqlc.arg(quota_type), sqlc.arg(delta), sqlc.arg(balance_after),
        sqlc.arg(reason), sqlc.arg(reference_type), sqlc.arg(reference_id))
RETURNING id;

-- name: CreateQuotaReservation :one
INSERT INTO quota_reservations (tenant_id, operator_id, quota_type, resource_type, resource_id, reserved_amount, status, expire_at)
VALUES (sqlc.arg(tenant_id), sqlc.arg(operator_id), sqlc.arg(quota_type), sqlc.arg(resource_type), sqlc.arg(resource_id),
        sqlc.arg(reserved_amount), 'pending', sqlc.arg(expire_at))
RETURNING id;

-- name: UpdateQuotaReservationResource :exec
UPDATE quota_reservations SET resource_id = sqlc.arg(resource_id), updated_at = NOW()
WHERE id = sqlc.arg(id) AND tenant_id = sqlc.arg(tenant_id);

-- name: ConfirmReservation :exec
UPDATE quota_reservations SET status = 'confirmed', consumed_amount = reserved_amount, updated_at = NOW()
WHERE id = sqlc.arg(id) AND tenant_id = sqlc.arg(tenant_id);

-- name: RefundReservation :exec
UPDATE quota_reservations SET status = 'refunded', refunded_amount = reserved_amount, updated_at = NOW()
WHERE id = sqlc.arg(id) AND tenant_id = sqlc.arg(tenant_id);
