import { z } from 'zod/v4';
import { CabinetEventType } from '../enums/cabinet-event.enums.js';

// --- Query ---

export const CabinetEventQuerySchema = z.object({
  medicineId: z.string().optional(),
  eventType: z.nativeEnum(CabinetEventType).optional(),
  startDate: z.iso.datetime().optional(),
  endDate: z.iso.datetime().optional(),
  cursor: z.string().optional(),
  limit: z.coerce.number().int().min(1).max(100).default(20),
});

export const SpendingSummaryQuerySchema = z.object({
  period: z.enum(['month', 'quarter', 'year']).default('month'),
  medicineId: z.string().optional(),
  startDate: z.iso.datetime().optional(),
  endDate: z.iso.datetime().optional(),
});

// --- Discard ---

export const DiscardCabinetItemSchema = z.object({
  reason: z.string().min(1).max(500).trim(),
  notes: z.string().max(1000).trim().optional(),
});

// --- Response ---

export const CabinetEventResponseSchema = z.object({
  _id: z.string(),
  householdId: z.string(),
  userId: z.string(),
  cabinetItemId: z.string(),
  medicineId: z.string(),
  medicineName: z.string(),
  eventType: z.string(),
  quantity: z.number(),
  quantityBefore: z.number(),
  quantityAfter: z.number(),
  unitPrice: z.number().optional(),
  totalPrice: z.number().optional(),
  currency: z.string().optional(),
  storeId: z.string().optional(),
  storeName: z.string().optional(),
  sourceType: z.string(),
  sourceId: z.string().optional(),
  reason: z.string().optional(),
  notes: z.string().optional(),
  createdAt: z.string(),
});

export const CabinetEventListResponseSchema = z.object({
  data: z.array(CabinetEventResponseSchema),
  pagination: z.object({
    cursor: z.string().nullable(),
    hasMore: z.boolean(),
    total: z.number().optional(),
  }),
});

export const SpendingByMedicineSchema = z.object({
  medicineId: z.string(),
  medicineName: z.string(),
  totalSpent: z.number(),
  totalQuantity: z.number(),
  avgUnitPrice: z.number(),
  purchaseCount: z.number(),
});

export const SpendingByPeriodSchema = z.object({
  period: z.string(),
  totalSpent: z.number(),
});

export const SpendingSummaryResponseSchema = z.object({
  totalSpent: z.number(),
  currency: z.string().nullable(),
  byMedicine: z.array(SpendingByMedicineSchema),
  byPeriod: z.array(SpendingByPeriodSchema),
});

// Type exports
export type CabinetEventQueryInput = z.infer<typeof CabinetEventQuerySchema>;
export type SpendingSummaryQueryInput = z.infer<typeof SpendingSummaryQuerySchema>;
export type DiscardCabinetItemInput = z.infer<typeof DiscardCabinetItemSchema>;
