import { Router, Request, Response, NextFunction } from 'express';
import { prisma } from '../../config/database';
import { pagesService } from './pages.service';

const router = Router();

// GET /api/pages/listed?page=1&limit=20 — get published + listed pages for public index (no auth, paginated)
router.get(
  '/listed',
  async (req: Request, res: Response, next: NextFunction) => {
    try {
      const page = Math.max(parseInt(req.query.page as string) || 1, 1);
      const limit = Math.min(parseInt(req.query.limit as string) || 20, 50);
      const where = { published: true, listed: true };
      const skip = (page - 1) * limit;

      const [pages, total] = await Promise.all([
        prisma.landingPage.findMany({
          where,
          select: {
            slug: true,
            title: true,
            description: true,
            seoImage: true,
            updatedAt: true,
          },
          orderBy: { updatedAt: 'desc' },
          skip,
          take: limit,
        }),
        prisma.landingPage.count({ where }),
      ]);

      res.json({
        pages,
        pagination: { page, limit, total, totalPages: Math.ceil(total / limit) },
      });
    } catch (err) {
      next(err);
    }
  }
);

// GET /api/pages/:slug/view — get published page by slug (public)
router.get(
  '/:slug/view',
  async (req: Request, res: Response, next: NextFunction) => {
    try {
      const slug = req.params.slug as string;
      const page = await pagesService.findBySlugPublic(slug);
      res.json(page);
    } catch (err) {
      next(err);
    }
  }
);

export { router as pagesPublicRouter };
