/**
 * Inbound message → task auto-create consumer — tasks-board-engine.
 *
 * Called from the comms-inbound queue consumer when a message arrives.
 * If task_sync_settings.auto_create_tickets_from[source] = true, creates a task.
 *
 * WhatsApp is Enterprise-tier only: additionally gates via meetsMinimumTier.
 *
 * Source: inbound messages via comms.inbound queue (type: 'comms.inbound')
 *   { tenantId, source, message: InboundMessage, receivedAt }
 *
 * task fields:
 *   title        = subject (email) or message.text (telegram/slack/whatsapp)
 *   description  = email body as plain JSON when present
 *   source       = message source
 *   project_id   = task_sync_settings.default_project_id
 *   reporter_id  = system sentinel (tenantId used as placeholder until system-user seeding lands)
 *   status_id    = first non-terminal tenant status
 *   position     = appended to column
 */
import { eq } from '@zync/db'
import { meetsMinimumTier } from '@zync/auth'
import type { InboundMessage, TenantId } from '@zync/types'
import { TenantTier } from '@zync/types'
import type { Db } from '@zync/db/queries'
import { taskSyncSettings, createTask, listStatuses, getTenantById, getTenantOwnerUserId } from '@zync/db/queries'

type InboundSource = 'email' | 'telegram' | 'slack' | 'whatsapp'

export interface InboundQueueMessage {
  type: 'comms.inbound'
  source: InboundSource
  tenantId: string
  message: InboundMessage & { subject?: string; body?: string }
  receivedAt: string
}

/**
 * Handle a single inbound message for task auto-creation.
 * Returns true if a task was created, false if skipped.
 */
export async function handleInboundForTasks(
  msg: InboundQueueMessage,
  db: Db,
): Promise<boolean> {
  const { tenantId, source, message } = msg

  // Load task sync settings for this tenant
  const [syncRow] = await db
    .select()
    .from(taskSyncSettings)
    .where(eq(taskSyncSettings.tenantId, tenantId))
    .limit(1)

  if (!syncRow) return false

  const autoCreate = syncRow.autoCreateTicketsFrom as Record<string, boolean>
  if (!autoCreate[source]) return false

  // WhatsApp: Enterprise-tier only
  if (source === 'whatsapp') {
    const tenant = await getTenantById(db, tenantId as TenantId)
    if (!tenant || !meetsMinimumTier(tenant.tier as TenantTier, TenantTier.ENTERPRISE)) {
      return false
    }
  }

  // Resolve first non-terminal status
  const statuses = await listStatuses(db, tenantId)
  const firstNonTerminal = statuses.find((s) => !s.is_terminal) ?? statuses[0]
  if (!firstNonTerminal) return false

  // Build task title and description from the inbound message
  let title: string
  let description: unknown | null = null

  if (source === 'email') {
    title = (message as { subject?: string }).subject ?? message.text
    if ((message as { body?: string }).body) {
      description = { type: 'doc', content: [{ type: 'paragraph', content: [{ type: 'text', text: (message as { body?: string }).body }] }] }
    }
  } else {
    title = message.text
  }

  if (!title) return false

  const reporterId = await getTenantOwnerUserId(db, tenantId)
  if (!reporterId) return false

  await createTask(db, tenantId, {
    title: title.slice(0, 500),
    description,
    status_id: firstNonTerminal.id,
    priority: 'medium',
    reporter_id: reporterId,
    project_id: syncRow.defaultProjectId ?? null,
    source: source as 'email' | 'telegram' | 'slack' | 'whatsapp',
    labels: [],
  })

  return true
}
