import { z } from 'zod';
import * as msgQ from '@/server/db/queries/support-messages.js';
import type { SupportTool, ToolResult } from './_types.js';
import type { AgentDeps } from '../types.js';

const inputSchema = z.object({
  parentType: z.enum(['ticket', 'case']),
  parentId: z.uuid(),
  text: z.string().min(1).max(5000),
  visibility: z.enum(['public', 'vendor_internal', 'site_internal']),
});

type Output = { messageId: string };

async function impl(deps: AgentDeps, rawInput: unknown): Promise<ToolResult<Output>> {
  const parsed = inputSchema.safeParse(rawInput);
  if (!parsed.success) return { ok: false, error: `INVALID_INPUT:${parsed.error.message}` };

  const { parentType, parentId, text, visibility } = parsed.data;

  // Gate: vendor_internal is not allowed for ticket parents or AI
  if (visibility === 'site_internal') {
    return { ok: false, error: 'AUTONOMY_GATE:ai_cannot_write_site_internal' };
  }
  if (visibility === 'vendor_internal' && parentType === 'ticket') {
    return { ok: false, error: 'AUTONOMY_GATE:vendor_internal_not_allowed_on_ticket' };
  }

  // De-anonymize any pseudo-ids in the text before storing
  const { substitutePseudoIds } = await import('../redactor.js');
  const plaintext = substitutePseudoIds(text, deps.redactionMap);

  const msg = await msgQ.insertEncrypted(
    deps.db,
    {
      parentType,
      parentId,
      authorType: 'ai',
      authorId: null,
      visibility,
    },
    plaintext,
    deps.piiKey,
  );

  return { ok: true, data: { messageId: msg.id } };
}

export const postMessageTool = {
  name: 'post_message',
  inputSchema,
  impl,
} satisfies SupportTool<'post_message', z.infer<typeof inputSchema>, Output>;
