import type { PoolClient } from 'pg'

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

/** 批量查询工单最近一次客服更新资料的时间，用于打手端"资料已更新"角标。 */
export async function getLatestMaterialEventAtByOrderIds(
  workOrderIds: number[],
): Promise<Map<number, string>> {
  if (workOrderIds.length === 0) return new Map()
  const result = await query<{ work_order_id: number; created_at: string }>(
    `
      SELECT DISTINCT ON (work_order_id) work_order_id, created_at
      FROM work_order_events
      WHERE work_order_id = ANY($1::bigint[])
        AND event_type IN ('material_updated', 'material_completed')
      ORDER BY work_order_id, id DESC
    `,
    [workOrderIds],
  )
  return new Map(result.rows.map((row) => [Number(row.work_order_id), String(row.created_at)]))
}

export type WorkOrderEventRow = {
  id: number
  work_order_id: number
  actor_type: string
  actor_id: string
  event_type: string
  from_status: string
  to_status: string
  payload_json: string | Record<string, unknown>
  created_at: string
}

export async function listWorkOrderEventsByOrderId(
  workOrderId: number | string,
): Promise<WorkOrderEventRow[]> {
  const result = await query<WorkOrderEventRow>(
    `
      SELECT *
      FROM work_order_events
      WHERE work_order_id = $1
      ORDER BY id ASC
    `,
    [Number(workOrderId)],
  )
  return result.rows
}

export async function createWorkOrderEvent(input: {
  workOrderId: number
  actorType: string
  actorId: string
  eventType: string
  fromStatus?: string
  toStatus?: string
  payloadJson?: string
  now: string
}): Promise<void> {
  await query(
    `
      INSERT INTO work_order_events (
        work_order_id, actor_type, actor_id, event_type, from_status, to_status, payload_json, created_at
      ) VALUES ($1, $2, $3, $4, $5, $6, $7::jsonb, $8)
    `,
    [
      input.workOrderId,
      input.actorType,
      input.actorId,
      input.eventType,
      input.fromStatus || '',
      input.toStatus || '',
      input.payloadJson || '{}',
      input.now,
    ],
  )
}

export async function createWorkOrderEventWithClient(
  client: PoolClient,
  input: Parameters<typeof createWorkOrderEvent>[0],
) {
  await client.query(
    `
      INSERT INTO work_order_events (
        work_order_id, actor_type, actor_id, event_type, from_status, to_status, payload_json, created_at
      ) VALUES ($1, $2, $3, $4, $5, $6, $7::jsonb, $8)
    `,
    [
      input.workOrderId,
      input.actorType,
      input.actorId,
      input.eventType,
      input.fromStatus || '',
      input.toStatus || '',
      input.payloadJson || '{}',
      input.now,
    ],
  )
}
