// src/routes/price.routes.ts
import { Router, Request, Response, NextFunction } from 'express';
import { z } from 'zod';
import passport from '../config/passport';
import { validateRequest } from '../middleware/validation.middleware';
import { priceRepo } from '../services/db/price.db';
import { optionalNumeric } from '../utils/zodUtils';
import { priceHistoryLimiter } from '../config/rateLimiters';
import { sendSuccess } from '../utils/apiResponse';

const router = Router();

const priceHistorySchema = z.object({
  body: z.object({
    masterItemIds: z.array(z.number().int().positive('Number must be greater than 0')).nonempty({
      message: 'masterItemIds must be a non-empty array of positive integers.',
    }),
    limit: optionalNumeric({ default: 1000, integer: true, positive: true }),
    offset: optionalNumeric({ default: 0, integer: true, nonnegative: true }),
  }),
});

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

/**
 * @openapi
 * /price-history:
 *   post:
 *     tags: [Price]
 *     summary: Get price history
 *     description: Fetches historical price data for a given list of master item IDs.
 *     security:
 *       - bearerAuth: []
 *     requestBody:
 *       required: true
 *       content:
 *         application/json:
 *           schema:
 *             type: object
 *             required:
 *               - masterItemIds
 *             properties:
 *               masterItemIds:
 *                 type: array
 *                 items:
 *                   type: integer
 *                 minItems: 1
 *                 description: Array of master item IDs to get price history for
 *               limit:
 *                 type: integer
 *                 default: 1000
 *                 description: Maximum number of price points to return
 *               offset:
 *                 type: integer
 *                 default: 0
 *                 description: Number of price points to skip
 *     responses:
 *       200:
 *         description: Historical price data for specified items
 *         content:
 *           application/json:
 *             schema:
 *               $ref: '#/components/schemas/SuccessResponse'
 *       400:
 *         description: Validation error - masterItemIds must be a non-empty array
 *       401:
 *         description: Unauthorized - invalid or missing token
 */
router.post(
  '/',
  passport.authenticate('jwt', { session: false }),
  priceHistoryLimiter,
  validateRequest(priceHistorySchema),
  async (req: Request, res: Response, next: NextFunction) => {
    // Cast 'req' to the inferred type for full type safety.
    const {
      body: { masterItemIds, limit, offset },
    } = req as unknown as PriceHistoryRequest;
    req.log.info(
      { itemCount: masterItemIds.length, limit, offset },
      '[API /price-history] Received request for historical price data.',
    );
    try {
      const priceHistory = await priceRepo.getPriceHistory(masterItemIds, req.log, limit, offset);
      sendSuccess(res, priceHistory);
    } catch (error) {
      next(error);
    }
  },
);

export default router;
