-- name: ListScheduleTasks :many
SELECT st.id, st.tenant_id, st.prompt_rule_id, st.brand_id, st.name,
       st.cron_expr, st.target_platform, st.start_at, st.end_at,
       st.next_run_at, st.status, st.created_at, st.updated_at,
       pr.name AS prompt_rule_name,
       b.name AS brand_name
FROM schedule_tasks st
LEFT JOIN prompt_rules pr ON pr.id = st.prompt_rule_id
LEFT JOIN brands b ON b.id = st.brand_id
WHERE st.tenant_id = sqlc.arg(tenant_id)
  AND st.deleted_at IS NULL
  AND (sqlc.narg(status)::text IS NULL OR st.status = sqlc.narg(status))
  AND (sqlc.narg(prompt_rule_id)::bigint IS NULL OR st.prompt_rule_id = sqlc.narg(prompt_rule_id))
ORDER BY st.created_at DESC
LIMIT sqlc.arg(page_size) OFFSET sqlc.arg(page_offset);

-- name: CountScheduleTasks :one
SELECT COUNT(*)
FROM schedule_tasks
WHERE tenant_id = sqlc.arg(tenant_id)
  AND deleted_at IS NULL
  AND (sqlc.narg(status)::text IS NULL OR status = sqlc.narg(status))
  AND (sqlc.narg(prompt_rule_id)::bigint IS NULL OR prompt_rule_id = sqlc.narg(prompt_rule_id));

-- name: GetScheduleTaskByID :one
SELECT st.id, st.tenant_id, st.prompt_rule_id, st.brand_id, st.name,
       st.cron_expr, st.target_platform, st.start_at, st.end_at,
       st.next_run_at, st.status, st.created_at, st.updated_at,
       pr.name AS prompt_rule_name,
       b.name AS brand_name
FROM schedule_tasks st
LEFT JOIN prompt_rules pr ON pr.id = st.prompt_rule_id
LEFT JOIN brands b ON b.id = st.brand_id
WHERE st.id = sqlc.arg(id) AND st.tenant_id = sqlc.arg(tenant_id) AND st.deleted_at IS NULL;

-- name: CreateScheduleTask :one
INSERT INTO schedule_tasks (tenant_id, prompt_rule_id, brand_id, name, cron_expr,
                            target_platform, start_at, end_at, next_run_at)
VALUES (sqlc.arg(tenant_id), sqlc.arg(prompt_rule_id), sqlc.narg(brand_id), sqlc.arg(name),
        sqlc.arg(cron_expr), sqlc.narg(target_platform), sqlc.narg(start_at), sqlc.narg(end_at),
        sqlc.narg(next_run_at))
RETURNING id, created_at;

-- name: UpdateScheduleTask :exec
UPDATE schedule_tasks
SET prompt_rule_id = sqlc.arg(prompt_rule_id), brand_id = sqlc.narg(brand_id),
    name = sqlc.arg(name), cron_expr = sqlc.arg(cron_expr),
    target_platform = sqlc.narg(target_platform),
    start_at = sqlc.narg(start_at), end_at = sqlc.narg(end_at),
    next_run_at = sqlc.narg(next_run_at), updated_at = NOW()
WHERE id = sqlc.arg(id) AND tenant_id = sqlc.arg(tenant_id) AND deleted_at IS NULL;

-- name: UpdateScheduleTaskStatus :exec
UPDATE schedule_tasks SET status = sqlc.arg(status), updated_at = NOW()
WHERE id = sqlc.arg(id) AND tenant_id = sqlc.arg(tenant_id) AND deleted_at IS NULL;

-- name: SoftDeleteScheduleTask :exec
UPDATE schedule_tasks SET deleted_at = NOW(), updated_at = NOW()
WHERE id = sqlc.arg(id) AND tenant_id = sqlc.arg(tenant_id) AND deleted_at IS NULL;
