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

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 }));

/**
 * @route GET /api/users/deals/best-watched-prices
 * @description Fetches the best current sale price for each of the authenticated user's watched items.
 * @access Private
 */
router.get('/best-watched-prices', validateRequest(bestWatchedPricesSchema), async (req: Request, res: Response, next: NextFunction) => {
  const user = 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(user.user_id, req.log);
    req.log.info({ dealCount: deals.length }, 'Successfully fetched best watched item deals.');
    res.status(200).json(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;