/**
 * Analytics Rollups module — types and schemas.
 * Pre-aggregated daily/weekly/monthly metrics per product.
 */

import { z } from 'zod';

export type RollupPeriod = 'daily' | 'weekly' | 'monthly';

export interface AnalyticsRollupDoc {
  id: string; // `${productId}:${period}:${date}`
  productId: string;
  period: RollupPeriod;
  date: string; // YYYY-MM-DD (daily), YYYY-Www (weekly), YYYY-MM (monthly)
  metrics: Record<string, number>;
  createdAt: string;
  updatedAt: string;
}

export interface MetricEvent {
  productId: string;
  metric: string; // e.g. 'signups', 'fasts_completed', 'timers_created'
  value: number;
  timestamp: string;
}

// ── Schemas ────────────────────────────────────────────────────

export const IngestMetricSchema = z.object({
  metric: z
    .string()
    .min(1)
    .max(100)
    .regex(/^[a-z0-9_.]+$/),
  value: z.number().default(1),
  timestamp: z.string().datetime().optional(),
});

export const IngestBatchSchema = z.object({
  events: z.array(IngestMetricSchema).min(1).max(100),
});

export const QueryRollupsSchema = z.object({
  period: z.enum(['daily', 'weekly', 'monthly']).default('daily'),
  from: z.string().optional(), // YYYY-MM-DD
  to: z.string().optional(), // YYYY-MM-DD
  metric: z.string().optional(), // filter to specific metric
});

export const AggregateRollupsSchema = z.object({
  targetPeriod: z.enum(['weekly', 'monthly']),
  sourceDate: z.string().optional(), // YYYY-MM-DD to aggregate from; defaults to yesterday
});

export const SummaryQuerySchema = z.object({
  days: z.coerce.number().int().min(1).max(365).default(30),
});

export const TopMetricsSchema = z.object({
  period: z.enum(['daily', 'weekly', 'monthly']).default('daily'),
  date: z.string().optional(), // specific date key; defaults to today
  limit: z.coerce.number().int().min(1).max(50).default(10),
});

export interface AnalyticsSummary {
  productId: string;
  days: number;
  totalEvents: number;
  uniqueMetrics: number;
  topMetrics: { metric: string; total: number }[];
  trend: { date: string; total: number }[];
}

export type IngestMetricInput = z.infer<typeof IngestMetricSchema>;
export type IngestBatchInput = z.infer<typeof IngestBatchSchema>;
export type QueryRollupsInput = z.infer<typeof QueryRollupsSchema>;
export type AggregateRollupsInput = z.infer<typeof AggregateRollupsSchema>;
export type SummaryQueryInput = z.infer<typeof SummaryQuerySchema>;
export type TopMetricsInput = z.infer<typeof TopMetricsSchema>;
