import type { Db, DbTx, PlatformSupportMessageRow } from '@zync/db/queries'
import {
  createPlatformSupportMessage,
  listPlatformSupportMessages,
} from '@zync/db/queries'

type DbLike = Db | DbTx

type TicketMessageSource = 'web' | 'email' | 'telegram' | 'whatsapp' | 'portal'
type TicketMessageAuthorType = 'staff' | 'customer' | 'system'
type TicketPriority = 'low' | 'medium' | 'high' | 'urgent'

export type LegacyTicketMessageInput = {
  author_type: TicketMessageAuthorType
  author_id?: string | null
  author_name?: string | null
  content: string
  source?: TicketMessageSource
}

export type PlatformTicketMessage = {
  id: string
  ticket_id: string
  tenant_id: string
  author_type: TicketMessageAuthorType
  author_id: string | null
  author_name: string | null
  content: string
  source: TicketMessageSource
  created_at: string
}

export type LegacyTicketRow = {
  id: string
  tenantId: string
  assigneeId: string | null
  resolvedAt: Date | null
  closedAt: Date | null
}

export type LegacyTicketMessageRow = {
  id: string
  ticketId: string
  tenantId: string
  authorType: TicketMessageAuthorType
  authorId: string | null
  authorName: string | null
  content: string
  source: TicketMessageSource
  deletedAt: Date | null
  createdAt: Date
}

export type LegacyTicketAttachmentRow = {
  id: string
  messageId: string
  tenantId: string
  filename: string
  r2Key: string
  url: string
  sizeBytes: number
  mimeType: string
  createdAt: Date
}

export type LegacySlaPolicyRow = {
  tenantId: string
  priority: TicketPriority
  firstResponseHours: number
  resolutionHours: number
}

export type PlatformMessageBackfillRow = {
  id: string
  parentType: 'ticket'
  parentId: string
  tenantId: string
  authorType: TicketMessageAuthorType
  authorId: string | null
  authorName: string | null
  body: string
  visibility: TicketMessageSource
  source: TicketMessageSource
  deletedAt: Date | null
  createdAt: Date
}

export type PlatformAttachmentBackfillRow = {
  id: string
  parentType: 'ticket_message'
  parentId: string
  tenantId: string
  messageId: string
  objectKey: string
  fileName: string
  mimeType: string
  url: string
  sizeBytes: number
  createdAt: Date
}

export type PlatformTransitionBackfillRow = {
  parentType: 'ticket'
  parentId: string
  tenantId: string
  fromStatus: string
  toStatus: string
  actorId: string
  reason: string
  at: Date
}

export type PlatformSlaPolicyBackfillRow = {
  scopeKey: string
  tenantId: string
  priority: TicketPriority
  target: 'resolution'
  dueMinutes: number
}

function mapPlatformMessageRow(row: PlatformSupportMessageRow): PlatformTicketMessage {
  return {
    id: row.id,
    ticket_id: row.ticketId,
    tenant_id: row.tenantId,
    author_type: row.authorType,
    author_id: row.authorId,
    author_name: row.authorName,
    content: row.content,
    source: row.source,
    created_at: row.createdAt.toISOString(),
  }
}

export async function createPlatformTicketMessage(
  db: DbLike,
  tenantId: string,
  ticketId: string,
  input: LegacyTicketMessageInput,
): Promise<PlatformTicketMessage> {
  const source = input.source ?? 'web'
  const row = await createPlatformSupportMessage(db, {
    tenantId,
    ticketId,
    authorType: input.author_type,
    authorId: input.author_id ?? null,
    authorName: input.author_name ?? null,
    content: input.content,
    source,
  })

  return mapPlatformMessageRow(row)
}

export async function listPlatformTicketMessages(
  db: DbLike,
  tenantId: string,
  ticketId: string,
): Promise<PlatformTicketMessage[]> {
  const rows = await listPlatformSupportMessages(db, {
    tenantId,
    ticketId,
  })

  return rows.map(mapPlatformMessageRow)
}

function buildTransitionBackfillRows(ticket: LegacyTicketRow): PlatformTransitionBackfillRow[] {
  const actorId = ticket.assigneeId ?? 'legacy-backfill'
  const rows: PlatformTransitionBackfillRow[] = []

  if (ticket.resolvedAt) {
    rows.push({
      parentType: 'ticket',
      parentId: ticket.id,
      tenantId: ticket.tenantId,
      fromStatus: 'open',
      toStatus: 'resolved',
      actorId,
      reason: 'legacy resolved backfill',
      at: ticket.resolvedAt,
    })
  }

  if (ticket.closedAt) {
    rows.push({
      parentType: 'ticket',
      parentId: ticket.id,
      tenantId: ticket.tenantId,
      fromStatus: ticket.resolvedAt ? 'resolved' : 'open',
      toStatus: 'closed',
      actorId,
      reason: 'legacy closed backfill',
      at: ticket.closedAt,
    })
  }

  return rows
}

export function buildPlatformHelpdeskBackfillRows(input: {
  tickets: LegacyTicketRow[]
  messages: LegacyTicketMessageRow[]
  attachments: LegacyTicketAttachmentRow[]
  slaPolicies: LegacySlaPolicyRow[]
}): {
  messages: PlatformMessageBackfillRow[]
  attachments: PlatformAttachmentBackfillRow[]
  transitions: PlatformTransitionBackfillRow[]
  slaPolicies: PlatformSlaPolicyBackfillRow[]
} {
  return {
    messages: input.messages.map((row) => ({
      id: row.id,
      parentType: 'ticket',
      parentId: row.ticketId,
      tenantId: row.tenantId,
      authorType: row.authorType,
      authorId: row.authorId,
      authorName: row.authorName,
      body: row.content,
      visibility: row.source,
      source: row.source,
      deletedAt: row.deletedAt,
      createdAt: row.createdAt,
    })),
    attachments: input.attachments.map((row) => ({
      id: row.id,
      parentType: 'ticket_message',
      parentId: row.messageId,
      tenantId: row.tenantId,
      messageId: row.messageId,
      objectKey: row.r2Key,
      fileName: row.filename,
      mimeType: row.mimeType,
      url: row.url,
      sizeBytes: row.sizeBytes,
      createdAt: row.createdAt,
    })),
    transitions: input.tickets.flatMap(buildTransitionBackfillRows),
    slaPolicies: input.slaPolicies.map((row) => ({
      scopeKey: `${row.tenantId}:${row.priority}:resolution`,
      tenantId: row.tenantId,
      priority: row.priority,
      target: 'resolution' as const,
      dueMinutes: row.resolutionHours * 60,
    })),
  }
}
