import { z } from 'zod';
import { eq, count } from 'drizzle-orm';
import { supportTickets, transactionCases } from '@/server/db/schema.js';
import type { SupportTool, ToolResult } from './_types.js';
import type { AgentDeps } from '../types.js';

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

type Output = { priorTickets: number; priorCases: 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 [ticketCount] = await deps.db
    .select({ cnt: count() })
    .from(supportTickets)
    .where(eq(supportTickets.openerId, parsed.data.userId));

  const [caseCount] = await deps.db
    .select({ cnt: count() })
    .from(transactionCases)
    .where(eq(transactionCases.customerId, parsed.data.userId));

  return {
    ok: true,
    data: {
      priorTickets: ticketCount?.cnt ?? 0,
      priorCases: caseCount?.cnt ?? 0,
    },
  };
}

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