-- name: CreateAuditLog :exec
INSERT INTO audit_logs (
    operator_id,
    tenant_id,
    module,
    action,
    resource_type,
    resource_id,
    request_id,
    before_json,
    after_json,
    result,
    error_message
)
VALUES (sqlc.arg(operator_id), sqlc.arg(tenant_id), sqlc.arg(module), sqlc.arg(action),
        sqlc.arg(resource_type), sqlc.arg(resource_id), sqlc.arg(request_id),
        sqlc.arg(before_json), sqlc.arg(after_json), sqlc.arg(result), sqlc.arg(error_message));

-- name: CreateGenerationTask :one
INSERT INTO generation_tasks (tenant_id, operator_id, article_id, task_batch_id, quota_reservation_id, task_type, request_hash, input_params_json, status)
VALUES (sqlc.arg(tenant_id), sqlc.arg(operator_id), sqlc.arg(article_id), sqlc.arg(task_batch_id),
        sqlc.arg(quota_reservation_id), sqlc.arg(task_type), sqlc.arg(request_hash), sqlc.arg(input_params_json), 'queued')
RETURNING id;

-- name: CreateTaskRecord :one
INSERT INTO task_records (tenant_id, operator_id, task_type, resource_type, resource_id, status)
VALUES (sqlc.arg(tenant_id), sqlc.arg(operator_id), sqlc.arg(task_type),
        sqlc.arg(resource_type), sqlc.arg(resource_id), sqlc.arg(status))
RETURNING id;

-- name: UpdateTaskRecordStatus :exec
UPDATE task_records
SET status = sqlc.arg(status),
    error_message = sqlc.arg(error_message),
    updated_at = NOW()
WHERE tenant_id = sqlc.arg(tenant_id)
  AND task_type = sqlc.arg(task_type)
  AND resource_type = sqlc.arg(resource_type)
  AND resource_id = sqlc.arg(resource_id);

-- name: UpdateGenerationTaskStatus :exec
UPDATE generation_tasks SET status = sqlc.arg(status)::text, error_message = sqlc.arg(error_message),
       started_at = COALESCE(sqlc.arg(started_at), started_at),
       completed_at = COALESCE(sqlc.arg(completed_at), completed_at),
       lease_token = CASE WHEN sqlc.arg(status)::text IN ('completed', 'failed') THEN NULL ELSE lease_token END,
       lease_owner = CASE WHEN sqlc.arg(status)::text IN ('completed', 'failed') THEN NULL ELSE lease_owner END,
       lease_expires_at = CASE WHEN sqlc.arg(status)::text IN ('completed', 'failed') THEN NULL ELSE lease_expires_at END,
       updated_at = NOW()
WHERE id = sqlc.arg(id) AND tenant_id = sqlc.arg(tenant_id);
