// 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';
import { optionalNumeric } from '../utils/zodUtils';

const router = Router();

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

// Define the query schema separately so we can use it to parse req.query in the handler
const statsQuerySchema = z.object({
  days: optionalNumeric({ default: 30, min: 1, max: 365, integer: true }),
  limit: optionalNumeric({ default: 10, min: 1, max: 50, integer: true }),
});

const mostFrequentSalesSchema = z.object({
  query: statsQuerySchema,
});

/**
 * 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 {
      // The `validateRequest` middleware ensures `req.query` is valid.
      // We parse it here to apply Zod's coercions (string to number) and defaults.
      const { days, limit } = statsQuerySchema.parse(req.query);
      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;
