-- name: CreateTask :one
INSERT INTO tasks (title, source, payload, external_provider, external_id, external_url, external_metadata)
VALUES ($1, $2, $3, $4, $5, $6, $7)
RETURNING id, title, source, status, payload, result, error, created_at, updated_at, external_provider, external_id, external_url, external_metadata;

-- name: GetTask :one
SELECT id, title, source, status, payload, result, error, created_at, updated_at, external_provider, external_id, external_url, external_metadata
FROM tasks
WHERE id::text = $1;

-- name: ListTasks :many
SELECT id, title, source, status, payload, result, error, created_at, updated_at, external_provider, external_id, external_url, external_metadata
FROM tasks
ORDER BY created_at DESC
LIMIT $1;

-- name: UpdateTaskStatus :one
UPDATE tasks
SET status = $2, updated_at = now()
WHERE id::text = $1
RETURNING id, title, source, status, payload, result, error, created_at, updated_at, external_provider, external_id, external_url, external_metadata;

-- name: CompleteTask :one
UPDATE tasks
SET status = 'completed', result = $2, error = NULL, updated_at = now()
WHERE id::text = $1
RETURNING id, title, source, status, payload, result, error, created_at, updated_at, external_provider, external_id, external_url, external_metadata;

-- name: FailTask :one
UPDATE tasks
SET status = 'failed', error = $2, updated_at = now()
WHERE id::text = $1
RETURNING id, title, source, status, payload, result, error, created_at, updated_at, external_provider, external_id, external_url, external_metadata;
