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

export async function listWorkerWorkOrderNotes(
  workerId: number | string,
  workOrderIds: number[],
): Promise<Array<{ work_order_id: number; note: string }>> {
  if (workOrderIds.length === 0) return []
  const result = await query<{ work_order_id: number; note: string }>(
    `
      SELECT work_order_id, note
      FROM worker_work_order_notes
      WHERE worker_id = $1 AND work_order_id = ANY($2::bigint[])
    `,
    [Number(workerId), workOrderIds],
  )
  return result.rows
}

export async function upsertWorkerWorkOrderNote(input: {
  workOrderId: number
  workerId: number
  note: string
  now: string
}): Promise<string> {
  const result = await query<{ note: string }>(
    `
      INSERT INTO worker_work_order_notes (
        work_order_id, worker_id, note, created_at, updated_at
      ) VALUES ($1, $2, $3, $4, $4)
      ON CONFLICT (work_order_id, worker_id) DO UPDATE
      SET note = EXCLUDED.note, updated_at = EXCLUDED.updated_at
      RETURNING note
    `,
    [input.workOrderId, input.workerId, input.note, input.now],
  )
  return String(result.rows[0]?.note || '')
}

/** 查询打手已查看过的工单，用于计算"新"标识与资料已更新角标。 */
export async function listWorkerWorkOrderViews(
  workerId: number | string,
  workOrderIds: number[],
): Promise<Array<{ work_order_id: number; viewed_at: string; material_seen_at: string | null }>> {
  if (workOrderIds.length === 0) return []
  const result = await query<{
    work_order_id: number
    viewed_at: string
    material_seen_at: string | null
  }>(
    `
      SELECT work_order_id, viewed_at, material_seen_at
      FROM worker_work_order_views
      WHERE worker_id = $1 AND work_order_id = ANY($2::bigint[])
    `,
    [Number(workerId), workOrderIds],
  )
  return result.rows
}

/**
 * 首次查看工单时写入已读记录，重复调用保持原查看时间不变；
 * materialSeen 为 true 时刷新资料查看时间，用于清除"资料已更新"角标。
 */
export async function markWorkerWorkOrderViewed(input: {
  workOrderId: number
  workerId: number
  now: string
  materialSeen?: boolean
}): Promise<string> {
  if (input.materialSeen) {
    await query(
      `
        INSERT INTO worker_work_order_views (work_order_id, worker_id, viewed_at, material_seen_at)
        VALUES ($1, $2, $3, $3)
        ON CONFLICT (work_order_id, worker_id) DO UPDATE
        SET material_seen_at = EXCLUDED.material_seen_at
      `,
      [input.workOrderId, input.workerId, input.now],
    )
  }
  const inserted = await query<{ viewed_at: string }>(
    `
      INSERT INTO worker_work_order_views (work_order_id, worker_id, viewed_at)
      VALUES ($1, $2, $3)
      ON CONFLICT (work_order_id, worker_id) DO NOTHING
      RETURNING viewed_at
    `,
    [input.workOrderId, input.workerId, input.now],
  )
  if (inserted.rows[0]?.viewed_at) return String(inserted.rows[0].viewed_at)
  const existing = await query<{ viewed_at: string }>(
    `
      SELECT viewed_at
      FROM worker_work_order_views
      WHERE work_order_id = $1 AND worker_id = $2
      LIMIT 1
    `,
    [input.workOrderId, input.workerId],
  )
  return String(existing.rows[0]?.viewed_at || input.now)
}
