import { z } from 'zod';
import { runSupportAgent } from '@/server/support/agent-runner.js';
import { captureCaught } from '@/server/observability/capture.server';
import type { SupportAgentRunInput } from '../../../ai/types.js';
import type { OutboxHandler } from '../types.js';

// Use a loose schema that accepts all SupportAgentRunInput fields plus extras.
// The payload is cast to SupportAgentRunInput for the agent calls.
const payloadSchema = z.object({
  parentType: z.enum(['ticket', 'case']).optional(),
  parentId: z.string().optional(),
  trigger: z.string().optional(),
});

type Payload = z.infer<typeof payloadSchema>;

export const supportAiDispatch: OutboxHandler<Payload> = {
  type: 'support.ai.dispatch',
  payloadSchema,
  async handle(ctx, payload, event) {
    if (!ctx.PII_KEY) {
      const msg = '[outbox] PII_KEY not configured for support.ai.dispatch';
      console.warn(
        JSON.stringify({ event: 'outbox_secret_missing', secret: 'PII_KEY', outboxId: event.id }),
      );
      if (ctx.strict !== false) throw new Error(msg);
      captureCaught(new Error(msg), { scope: 'outbox.dispatch.support_ai', severity: 'warning' });
      return;
    }

    // Cast to SupportAgentRunInput — the producer always writes this shape.
    // The loose schema ensures in-flight legacy payloads don't fail validation.
    const agentInput = payload as unknown as SupportAgentRunInput;

    await runSupportAgent(
      {
        DATABASE_URL: ctx.DATABASE_URL,
        PII_KEY: ctx.PII_KEY,
        TOPIC_DO: ctx.TOPIC_DO,
      },
      agentInput,
    );
  },
};
