import { z } from 'zod';
import * as actionsQ from '@/server/db/queries/support/ai-actions.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(),
  level: z.enum(['low', 'normal', 'high', 'urgent']),
});

type Output = { updated: true };

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 { parentType, parentId, level } = parsed.data;

  if (parentType === 'ticket') {
    await actionsQ.setPriority(deps.db, parentId, level);
  }
  // Cases don't have a priority field — silently succeed

  return { ok: true, data: { updated: true } };
}

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