-- name: CreateKolAssistTask :exec
INSERT INTO kol_assist_tasks (id, tenant_id, kol_profile_id, prompt_id,
                              operator_id, task_type, status, request_json)
VALUES (sqlc.arg(id), sqlc.arg(tenant_id)::bigint, sqlc.arg(kol_profile_id),
        sqlc.arg(prompt_id), sqlc.arg(operator_id),
        sqlc.arg(task_type), 'queued', sqlc.arg(request_json)::jsonb);

-- name: GetKolAssistTask :one
SELECT id, tenant_id, kol_profile_id, prompt_id, operator_id, task_type,
       status, request_json, result_json, error_message,
       started_at, completed_at, created_at, updated_at
FROM kol_assist_tasks
WHERE id = sqlc.arg(id)
  AND tenant_id = sqlc.arg(tenant_id)::bigint;

-- name: MarkKolAssistStarted :exec
UPDATE kol_assist_tasks
SET status = 'running', started_at = NOW(), updated_at = NOW()
WHERE id = sqlc.arg(id)
  AND tenant_id = sqlc.arg(tenant_id)::bigint;

-- name: MarkKolAssistCompleted :exec
UPDATE kol_assist_tasks
SET status = 'completed', result_json = sqlc.arg(result_json)::jsonb,
    completed_at = NOW(), updated_at = NOW()
WHERE id = sqlc.arg(id)
  AND tenant_id = sqlc.arg(tenant_id)::bigint;

-- name: MarkKolAssistFailed :exec
UPDATE kol_assist_tasks
SET status = 'failed', error_message = sqlc.arg(error_message),
    completed_at = NOW(), updated_at = NOW()
WHERE id = sqlc.arg(id)
  AND tenant_id = sqlc.arg(tenant_id)::bigint;
