// src/routes/deals.routes.ts
import express, { type Request, type Response, type NextFunction } from 'express';
import { z } from 'zod';
import passport from '../config/passport';
import { dealsRepo } from '../services/db/deals.db';
import type { UserProfile } from '../types';
import { validateRequest } from '../middleware/validation.middleware';
import { userReadLimiter } from '../config/rateLimiters';
import { sendSuccess } from '../utils/apiResponse';

const router = express.Router();

// --- Zod Schemas for Deals Routes (as per ADR-003) ---

const bestWatchedPricesSchema = z.object({
  // No params, query, or body expected for this route currently.
});

// --- Middleware for all deal routes ---

// Per ADR-002, all routes in this file require an authenticated user.
// We apply the standard passport JWT middleware at the router level.
router.use(passport.authenticate('jwt', { session: false }));

/**
 * @openapi
 * /deals/best-watched-prices:
 *   get:
 *     tags: [Deals]
 *     summary: Get best prices for watched items
 *     description: Fetches the best current sale price for each of the authenticated user's watched items.
 *     security:
 *       - bearerAuth: []
 *     responses:
 *       200:
 *         description: List of best prices for watched items
 *         content:
 *           application/json:
 *             schema:
 *               $ref: '#/components/schemas/SuccessResponse'
 *       401:
 *         description: Unauthorized - invalid or missing token
 */
router.get(
  '/best-watched-prices',
  userReadLimiter,
  validateRequest(bestWatchedPricesSchema),
  async (req: Request, res: Response, next: NextFunction) => {
    const userProfile = req.user as UserProfile;
    try {
      // The controller logic is simple enough to be handled directly in the route,
      // consistent with other simple GET routes in the project.
      const deals = await dealsRepo.findBestPricesForWatchedItems(
        userProfile.user.user_id,
        req.log,
      );
      req.log.info({ dealCount: deals.length }, 'Successfully fetched best watched item deals.');
      sendSuccess(res, deals);
    } catch (error) {
      req.log.error({ error }, 'Error fetching best watched item deals.');
      next(error); // Pass errors to the global error handler
    }
  },
);

export default router;
