// src/routes/stats.routes.ts
import { Router, Request, Response, NextFunction } from 'express';
import { z } from 'zod';
import * as db from '../services/db/index.db';
import { validateRequest } from '../middleware/validation.middleware';

const router = Router();

// --- Zod Schema for Stats Routes (as per ADR-003) ---

const mostFrequentSalesSchema = z.object({
  query: z.object({
    days: z.coerce.number().int().min(1).max(365).optional().default(30),
    limit: z.coerce.number().int().min(1).max(50).optional().default(10),
  }),
});

// Infer the type from the schema for local use, as per ADR-003.
type MostFrequentSalesRequest = z.infer<typeof mostFrequentSalesSchema>;

/**
 * GET /api/stats/most-frequent-sales - Get a list of items that have been on sale most frequently.
 * This is a public endpoint for data analysis.
 */
router.get('/most-frequent-sales', validateRequest(mostFrequentSalesSchema), async (req: Request, res: Response, next: NextFunction) => {
    try {
        const { query } = req as unknown as MostFrequentSalesRequest;
        const days = query.days !== undefined ? Number(query.days) : 30;
        const limit = query.limit !== undefined ? Number(query.limit) : 10;
        const items = await db.adminRepo.getMostFrequentSaleItems(days, limit, req.log);
        res.json(items);
    } catch (error) {
        req.log.error({ error }, 'Error fetching most frequent sale items in /api/stats/most-frequent-sales:');
        next(error);
    }
});

export default router;