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

const inputSchema = z.object({ id: z.uuid() });

type Output = {
  id: string;
  status: string;
  category: string;
  orderLineId: string;
  escapeUsed: boolean;
  reopenCount: 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 c = await caseQ.findById(deps.db, parsed.data.id);
  if (!c) return { ok: false, error: 'NOT_FOUND:case' };

  // PII stripped — customerId / vendorId replaced by pseudo-ids via redaction map
  return {
    ok: true,
    data: {
      id: c.id,
      status: c.status,
      category: c.category,
      orderLineId: c.orderLineId,
      escapeUsed: c.escapeUsed,
      reopenCount: c.reopenCount,
    },
  };
}

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