import { query } from '../db/client.js'

type TaskEventRow = {
  [column: string]: unknown
  id: number
  task_id: number
  event_type: string
  payload_json: string | Record<string, unknown>
  created_at: string
}

type TaskEventListOptions = {
  limit?: number | string
}

export async function createTaskEvent(
  taskId: number | string,
  eventType: string,
  payload: unknown = {},
  createdAt: string | undefined = undefined,
): Promise<TaskEventRow | null> {
  const result = await query<TaskEventRow>(
    `
      INSERT INTO task_events (
        task_id,
        event_type,
        payload_json,
        created_at
      ) VALUES ($1, $2, $3::jsonb, $4)
      RETURNING *
    `,
    [Number(taskId), String(eventType || '').trim(), JSON.stringify(payload || {}), createdAt],
  )

  return result.rows[0] || null
}

export async function listTaskEventsByTaskId(
  taskId: number | string,
  { limit = 20 }: TaskEventListOptions = {},
): Promise<TaskEventRow[]> {
  const result = await query<TaskEventRow>(
    `
      SELECT *
      FROM task_events
      WHERE task_id = $1
      ORDER BY created_at DESC, id DESC
      LIMIT $2
    `,
    [Number(taskId), Math.max(1, Number(limit || 20))],
  )

  return result.rows
}
