-- name: CreateTask :one
INSERT INTO tasks (title, source, payload, metadata, external_provider, external_id, external_url, external_metadata)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8)
ON CONFLICT (external_provider, external_id) WHERE external_provider IS NOT NULL AND external_id IS NOT NULL
DO UPDATE SET updated_at = tasks.updated_at
RETURNING id, title, source, status, payload, result, error, created_at, updated_at, external_provider, external_id, external_url, external_metadata, metadata;

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

-- name: GetTask :one
SELECT id, title, source, status, payload, result, error, created_at, updated_at, external_provider, external_id, external_url, external_metadata, 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, 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, metadata;

-- name: UpdateTaskMetadata :one
UPDATE tasks
SET metadata = $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, 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, 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, metadata;
