import { z } from 'zod';

/** Bibliothèque de documents (R3) — types fermés, rattachement obligatoire. */

export const DOCUMENT_KINDS = ['NOTICE', 'CERTIFICATE', 'PHOTO', 'OTHER'] as const;
export type DocumentKind = (typeof DOCUMENT_KINDS)[number];
export const DOCUMENT_KIND_LABELS: Record<DocumentKind, string> = {
  NOTICE: 'Notice',
  CERTIFICATE: 'Certificat',
  PHOTO: 'Photo',
  OTHER: 'Autre',
};

export const DOCUMENT_MAX_BYTES = 20 * 1024 * 1024; // 20 Mo
export const DOCUMENT_CONTENT_TYPES = [
  'application/pdf',
  'image/jpeg',
  'image/png',
] as const;

export const DocumentSchema = z.object({
  id: z.uuid(),
  kind: z.enum(DOCUMENT_KINDS),
  fileName: z.string(),
  size: z.number().int(),
  contentType: z.string(),
  assetReference: z.string().nullable(),
  workOrderReference: z.string().nullable(),
  uploadedByName: z.string().nullable(),
  createdAt: z.iso.datetime(),
  /** R5 (D3) : corpus visible et réversible, document par document. */
  inCorpus: z.boolean(),
  indexedAt: z.iso.datetime().nullable(), // null = jamais indexé
  chunkCount: z.number().int(),
});
export type DocumentDto = z.infer<typeof DocumentSchema>;

export const DocumentCorpusUpdateSchema = z.object({
  inCorpus: z.boolean(),
});
export type DocumentCorpusUpdate = z.infer<typeof DocumentCorpusUpdateSchema>;

export const DocumentsResponseSchema = z.object({
  documents: z.array(DocumentSchema),
});
export type DocumentsResponse = z.infer<typeof DocumentsResponseSchema>;

// ————— Analytics (écran Statistiques, maquette R3) —————

export const ANALYTICS_PERIODS = [3, 6, 12] as const;
export type AnalyticsPeriod = (typeof ANALYTICS_PERIODS)[number];

export const AnalyticsSummarySchema = z.object({
  months: z.number().int(), // période appliquée (3, 6 ou 12 mois)
  monthCost: z.number(), // MAD, mois courant (pièces + main-d'œuvre)
  previousMonthCost: z.number(),
  closed: z.object({ total: z.number().int(), preventive: z.number().int() }),
  preventiveRate: z.number().nullable(), // grilles terminées / générées (période)
  avgResolutionDays: z.number().nullable(), // dépannages terminés (période)
  failuresByComponent: z.array(
    z.object({ label: z.string(), count: z.number().int() }),
  ),
  costsByMonth: z.array(z.object({ month: z.string(), total: z.number() })), // un point par mois de la période
  topAssets: z.array(
    z.object({
      reference: z.string(),
      siteName: z.string(),
      correctives: z.number().int(),
      partsCost: z.number(),
      laborCost: z.number(),
      total: z.number(),
    }),
  ),
});
export type AnalyticsSummary = z.infer<typeof AnalyticsSummarySchema>;
