-- name: EnsureImageStorageUsageRow :exec
INSERT INTO tenant_image_storage_usage (tenant_id, used_bytes)
VALUES (sqlc.arg(tenant_id), 0)
ON CONFLICT (tenant_id) DO NOTHING;

-- name: GetImageStorageUsage :one
SELECT used_bytes, updated_at
FROM tenant_image_storage_usage
WHERE tenant_id = sqlc.arg(tenant_id);

-- name: ReleaseImageStorageQuota :exec
UPDATE tenant_image_storage_usage
SET used_bytes = GREATEST(0, used_bytes - sqlc.arg(release_bytes)),
    updated_at = NOW()
WHERE tenant_id = sqlc.arg(tenant_id);
