import { z } from "zod";
import { DATE_KINDS, INVENTORY_SOURCES, INVENTORY_TRANSACTION_TYPES } from "@app/shared-types";
import { dateStringSchema, quantitySchema, unitSchema, uuidSchema } from "./common.js";

export const createInventoryItemInputSchema = z.object({
  canonicalIngredientId: z.string().max(80).optional(),
  productId: uuidSchema.optional(),
  displayName: z.string().min(1).max(120).trim(),
  brand: z.string().max(80).optional(),
  quantity: quantitySchema,
  unit: unitSchema,
  storageLocationId: uuidSchema,
  sublocation: z.string().max(60).optional(),
  purchasedAt: dateStringSchema.optional(),
  openedAt: dateStringSchema.optional(),
  bestBeforeDate: dateStringSchema.optional(),
  useByDate: dateStringSchema.optional(),
  dateKind: z.enum(DATE_KINDS).optional(),
  frozenAt: dateStringSchema.optional(),
  priceMinor: z.number().int().min(0).max(10_000_000).optional(),
  source: z.enum(INVENTORY_SOURCES).default("manual_search"),
});
export type CreateInventoryItemInput = z.infer<typeof createInventoryItemInputSchema>;

export const updateInventoryItemInputSchema = createInventoryItemInputSchema.partial().extend({
  verifiedByUser: z.boolean().optional(),
});
export type UpdateInventoryItemInput = z.infer<typeof updateInventoryItemInputSchema>;

/** Manuell lagertransaktion, t.ex. "använde 300 g" eller "slängde resten". */
export const inventoryTransactionInputSchema = z.object({
  type: z.enum(INVENTORY_TRANSACTION_TYPES),
  quantityDelta: z.number().refine((v) => v !== 0, "Delta får inte vara 0"),
  note: z.string().max(200).optional(),
});
export type InventoryTransactionInput = z.infer<typeof inventoryTransactionInputSchema>;

export const inventoryQuerySchema = z.object({
  storageLocationId: uuidSchema.optional(),
  expiryStatus: z.enum(["fresh", "use_soon", "expiring", "expired", "unknown"]).optional(),
  search: z.string().max(80).optional(),
  limit: z.coerce.number().int().min(1).max(200).default(100),
  offset: z.coerce.number().int().min(0).default(0),
});
export type InventoryQuery = z.infer<typeof inventoryQuerySchema>;
