import { Router, Request, Response, NextFunction } from 'express';
import { prisma } from '../../config/database';
import { galleryAdsService } from './gallery-ads.service';
import { trackAdSchema, publicAdsQuerySchema } from './gallery-ads.schemas';
import { validate } from '../../middleware/validate';
import { optionalAuth } from '../../middleware/auth.middleware';
import { adTrackingRateLimit } from '../../middleware/rate-limit';

const router = Router();

// GET /api/gallery-ads — get active ads for current viewer
router.get('/', optionalAuth, async (req: Request, res: Response, next: NextFunction) => {
  try {
    const isAuthenticated = !!req.user;
    let hasActiveSubscription = false;

    if (req.user) {
      const sub = await prisma.userSubscription.findFirst({
        where: {
          userId: req.user.id,
          status: 'active',
          endDate: { gte: new Date() },
        },
      });
      hasActiveSubscription = !!sub;
    }

    const query = publicAdsQuerySchema.safeParse(req.query);
    const placement = query.success ? query.data.placement : undefined;

    const ads = await galleryAdsService.getActiveAds({
      isAuthenticated,
      hasActiveSubscription,
      placement,
    });

    res.json(ads);
  } catch (err) {
    next(err);
  }
});

// POST /api/gallery-ads/track — record impression or click
router.post(
  '/track',
  adTrackingRateLimit,
  optionalAuth,
  validate(trackAdSchema),
  async (req: Request, res: Response, next: NextFunction) => {
    try {
      const { adId, event, sessionId } = req.body;
      const userId = req.user?.id;

      if (event === 'impression') {
        await galleryAdsService.recordImpression(adId, sessionId, userId);
      } else {
        await galleryAdsService.recordClick(adId, sessionId, userId);
      }

      res.json({ success: true });
    } catch {
      // Silent fail for tracking — non-critical
      res.json({ success: true });
    }
  }
);

export { router as galleryAdsPublicRouter };
