/**
 * Template Style Routes — Public (authenticated)
 *
 * Exposes only ENABLED template styles to the Landing Page builder so users can
 * pick a marketing style before AI generation. Read-only.
 * Mounted at: /api/template-styles
 *
 * NOTE: Do NOT use `router.use(authenticate)` here.
 * This router is mounted at `/api` (see index.ts), so a router-level
 * `router.use(authenticate)` would run on EVERY `/api/*` request — including
 * unauthenticated ones such as the website-generator preview iframe
 * (`/api/website-generator/preview-website/:websiteId`), which cannot send a
 * Bearer token. That would block those public routes with a 401 before they
 * are reached. Apply `authenticate` per-route instead.
 */

import { Router, Request, Response } from 'express';
import { getModels } from '../models';
import { authenticate } from '../middleware/auth';

const router = Router();

// GET /template-styles — list enabled templates (for the landing page builder)
router.get('/template-styles', authenticate, async (_req: Request, res: Response) => {
  try {
    const { TemplateStyle } = getModels();
    const templates = await TemplateStyle
      .find({ enabled: true })
      .sort({ displayOrder: 1, createdAt: 1 })
      .lean();
    res.json(templates);
  } catch (error: any) {
    console.error('[TemplateStyles] List enabled error:', error.message);
    res.status(500).json({ error: 'Failed to fetch template styles' });
  }
});

// GET /template-styles/:id — single enabled template
router.get('/template-styles/:id', authenticate, async (req: Request, res: Response) => {
  try {
    const { TemplateStyle } = getModels();
    const template = await TemplateStyle.findById(req.params.id).lean();
    if (!template || !template.enabled) {
      res.status(404).json({ error: 'Template style not found' });
      return;
    }
    res.json(template);
  } catch (error: any) {
    console.error('[TemplateStyles] Get enabled error:', error.message);
    res.status(500).json({ error: 'Failed to fetch template style' });
  }
});

export default router;
