import { z } from 'zod';
import * as attachQ from '@/server/db/queries/support-attachments.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(),
});

type Output = Array<{ id: string; mime: string; sizeBytes: number }>;

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 rows = await attachQ.listByParent(deps.db, parsed.data.parentType, parsed.data.parentId);

  return {
    ok: true,
    data: rows.map((r) => ({ id: r.id, mime: r.mime, sizeBytes: r.sizeBytes })),
  };
}

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