/**
 * SupportTicket lifecycle alarm handler.
 *
 * Called from SupportTicketDO.alarm() with the ticketId.
 *
 * Two possible alarm scenarios (determined by current ticket status):
 *   - status = 'resolved'       → autoclose alarm → transition to 'closed'
 *   - status in active statuses → SLA deadline alarm → log SLA breach (no
 *     state transition; human agent must act). Phase 5 adds AI triage here.
 *
 * Inserts a support_state_transitions row for audit; enqueues an outbox
 * event so the notification worker sends the appropriate email/push.
 */

import { eq } from 'drizzle-orm';
import type { DoDbClient } from '../lib/db.js';
import { supportTickets } from '@/server/db/schema';
import { insert as insertSupportStateTransition } from '@/server/db/queries/support-state-transitions.js';
import { autocloseSupportTicketWithTransition } from '@/server/db/queries/do-lifecycle.js';

export interface SupportTicketAlarmDeps {
  db: DoDbClient;
  enqueueOutbox: (kind: string, body: unknown) => Promise<void>;
}

async function insertTransition(
  db: DoDbClient,
  ticketId: string,
  fromState: string,
  toState: string,
  reason: string,
): Promise<void> {
  await insertSupportStateTransition(db, {
    parentType: 'ticket',
    parentId: ticketId,
    fromState,
    toState,
    actorType: 'system',
    actorId: null,
    reason,
    metadata: {},
  });
}

export async function handleSupportTicketAlarm(
  deps: SupportTicketAlarmDeps,
  ticketId: string,
): Promise<{ acted: boolean; action?: string }> {
  const { db, enqueueOutbox } = deps;

  const [row] = await db
    .select()
    .from(supportTickets)
    .where(eq(supportTickets.id, ticketId))
    .limit(1);

  if (!row) {
    return { acted: false };
  }

  // ─── Autoclose: resolved → closed ────────────────────────────────────────
  if (row.status === 'resolved') {
    await autocloseSupportTicketWithTransition(db, ticketId);

    await enqueueOutbox('support.ticket.autoclosed', { ticketId });

    return { acted: true, action: 'autoclose' };
  }

  // ─── SLA breach: active statuses ─────────────────────────────────────────
  const ACTIVE_STATUSES = new Set([
    'open',
    'ai_handling',
    'awaiting_user',
    'escalated',
    'awaiting_agent',
    'human_handling',
  ]);

  if (ACTIVE_STATUSES.has(row.status)) {
    await insertTransition(db, ticketId, row.status, row.status, 'sla_deadline_passed');

    await enqueueOutbox('support.ticket.sla_breached', { ticketId, status: row.status });

    // Phase 5: trigger AI triage on SLA breach for AI-handled tickets
    if (row.status === 'open' || row.status === 'ai_handling' || row.status === 'awaiting_user') {
      await enqueueOutbox('support.ai.dispatch', {
        parentType: 'ticket',
        parentId: ticketId,
        trigger: 'escalated',
      });
    }

    return { acted: true, action: 'sla_breach_logged' };
  }

  // Already closed or in a terminal state — alarm fired late, no-op
  return { acted: false };
}
