import { z } from "zod";

/** Empty strings from the LLM become undefined so optional fields stay clean. */
const optionalText = (max: number) =>
  z
    .string()
    .trim()
    .max(max)
    .optional()
    .transform((v) => (v ? v : undefined));

export const FlagCategorySchema = z.enum([
  "KNOWLEDGE_GAP",
  "WRONG_INFO",
  "DATA_UPDATE_REQUEST",
  "ESCALATION",
  "OTHER",
]);

/** Body of POST /v1/kevo/tools/flag-issue — called by the ElevenLabs agent. */
export const FlagIssueSchema = z.object({
  category: FlagCategorySchema,
  member_question: z.string().trim().min(1).max(4000),
  agent_answer: optionalText(4000),
  member_claim: optionalText(4000),
  entity: optionalText(190),
  requested_change: optionalText(4000),
  conversation_id: z.string().trim().min(1).max(190),
  member_id: optionalText(190),
});

export type FlagIssueInput = z.infer<typeof FlagIssueSchema>;

export const FlagStatusSchema = z.enum([
  "NEW",
  "IN_REVIEW",
  "APPROVED",
  "REJECTED",
  "PUBLISHED",
  "ROUTED",
  "RESOLVED",
]);
export const FlagSourceSchema = z.enum(["IN_CALL", "POST_CALL", "MANUAL"]);

/** Body of POST /v1/admin-console/kevo/flags/list (filter-heavy read). */
export const ListFlagsSchema = z.object({
  categories: z.array(FlagCategorySchema).optional(),
  statuses: z.array(FlagStatusSchema).optional(),
  sources: z.array(FlagSourceSchema).optional(),
  entity: optionalText(190),
  search: optionalText(190),
  date_from: z.string().optional(),
  date_to: z.string().optional(),
  page: z.number().int().min(1).default(1),
  limit: z.number().int().min(1).max(100).default(25),
});

export const UpdateFlagSchema = z
  .object({
    status: FlagStatusSchema.optional(),
    reviewer_notes: optionalText(4000),
  })
  .refine((v) => v.status || v.reviewer_notes, {
    message: "Provide a status or reviewer notes",
  });

export const KnowledgeUpsertSchema = z.object({
  flag_id: z.string().uuid().optional(),
  entity: z.string().trim().min(1).max(190),
  aliases: z.array(z.string().trim().min(1).max(190)).max(20).default([]),
  property: optionalText(190),
  category: z.enum(["amenity", "policy", "faq", "correction"]),
  verified_text: z.string().trim().min(1).max(4000),
});

export const KnowledgeListSchema = z.object({
  statuses: z
    .array(z.enum(["DRAFT", "APPROVED", "PUBLISHED", "RETIRED"]))
    .optional(),
  property: optionalText(190),
  search: optionalText(190),
});

export type ListFlagsInput = z.infer<typeof ListFlagsSchema>;
export type UpdateFlagInput = z.infer<typeof UpdateFlagSchema>;
export type KnowledgeUpsertInput = z.infer<typeof KnowledgeUpsertSchema>;
