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

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

type Output = { 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 [caseCount] = await deps.db
    .select({ cnt: count() })
    .from(transactionCases)
    .where(eq(transactionCases.vendorId, parsed.data.vendorId));

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

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