import { z } from 'zod';
import * as ticketQ from '@/server/db/queries/support-tickets.js';
import type { SupportTool, ToolResult } from './_types.js';
import type { AgentDeps } from '../types.js';
import { type SupportOpenerRole } from '@/lib/enums/support-opener-role';

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

type Output = {
  id: string;
  status: string;
  category: string;
  priority: string;
  openerRole: SupportOpenerRole;
  reopenCount: number;
  relatedOrderLineId: string | null;
};

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 ticket = await ticketQ.findById(deps.db, parsed.data.id);
  if (!ticket) return { ok: false, error: 'NOT_FOUND:ticket' };

  return {
    ok: true,
    data: {
      id: ticket.id,
      status: ticket.status,
      category: ticket.category,
      priority: ticket.priority,
      openerRole: ticket.openerRole,
      reopenCount: ticket.reopenCount,
      relatedOrderLineId: ticket.relatedOrderLineId,
    },
  };
}

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