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(),
  what: z.string().min(1).max(500),
  templateKey: z.string().optional(),
});

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, what } = parsed.data;

  // Post a public message requesting the evidence
  const msg = await msgQ.insertEncrypted(
    deps.db,
    {
      parentType,
      parentId,
      authorType: 'ai',
      authorId: null,
      visibility: 'public',
    },
    what,
    deps.piiKey,
  );

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

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