const express = require('express');
const router = express.Router();
const { Category, Product, ProductImage, ProductVariant, Banner, Page, Review, Setting, User } = require('../models');
const { Op } = require('sequelize');
const appConfig = require('../config/app');

// Homepage
router.get('/', async (req, res) => {
  try {
    const featuredProducts = await Product.findAll({
      where: { isFeatured: true, isActive: true },
      include: [{ model: ProductImage, as: 'images', where: { isPrimary: true }, required: false }],
      limit: 8,
      order: [['createdAt', 'DESC']],
    });

    const categories = await Category.findAll({
      where: { isActive: true, parentId: null },
      include: [{ model: Category, as: 'children' }],
      order: [['sortOrder', 'ASC']],
      limit: 6,
    });

    const banners = await Banner.findAll({
      where: { isActive: true },
      order: [['sortOrder', 'ASC']],
    });

    const newArrivals = await Product.findAll({
      where: { isActive: true },
      include: [{ model: ProductImage, as: 'images', where: { isPrimary: true }, required: false }],
      limit: 4,
      order: [['createdAt', 'DESC']],
    });

    res.render('index', { title: 'Home', featuredProducts, categories, banners, newArrivals });
  } catch (error) {
    console.error('Homepage error:', error);
    res.redirect('/products');
  }
});

// Product catalog
router.get('/products', async (req, res) => {
  try {
    const { category, search, sort, page = 1, minPrice, maxPrice } = req.query;
    const limit = 12;
    const offset = (parseInt(page) - 1) * limit;

    const where = { isActive: true };
    if (category) where.categoryId = category;
    if (search) {
      where[Op.or] = [
        { name: { [Op.like]: `%${search}%` } },
        { description: { [Op.like]: `%${search}%` } },
      ];
    }
    if (minPrice) where.price = { ...where.price, [Op.gte]: parseFloat(minPrice) };
    if (maxPrice) where.price = { ...where.price, [Op.lte]: parseFloat(maxPrice) };

    let order = [['createdAt', 'DESC']];
    if (sort === 'price_asc') order = [['price', 'ASC']];
    if (sort === 'price_desc') order = [['price', 'DESC']];
    if (sort === 'name') order = [['name', 'ASC']];
    if (sort === 'newest') order = [['createdAt', 'DESC']];

    const { count, rows: products } = await Product.findAndCountAll({
      where,
      include: [
        { model: ProductImage, as: 'images', where: { isPrimary: true }, required: false },
        { model: Category },
      ],
      order,
      limit,
      offset,
    });

    const categories = await Category.findAll({ where: { isActive: true }, order: [['name', 'ASC']] });

    res.render('catalog', {
      title: search ? `Search: ${search}` : 'Products',
      products,
      categories,
      currentCategory: category,
      search,
      sort,
      currentPage: parseInt(page),
      totalPages: Math.ceil(count / limit),
      total: count,
      minPrice,
      maxPrice,
    });
  } catch (error) {
    console.error('Catalog error:', error);
    req.flash('error', 'Error loading products.');
    res.redirect('/');
  }
});

// Product detail
router.get('/products/:slug', async (req, res) => {
  try {
    const product = await Product.findOne({
      where: { slug: req.params.slug, isActive: true },
      include: [
        { model: ProductImage, as: 'images', order: [['sortOrder', 'ASC']] },
        { model: ProductVariant, as: 'variants', where: { isActive: true }, required: false },
        { model: Category },
        {
          model: Review,
          where: { isApproved: true },
          required: false,
          limit: 10,
          order: [['createdAt', 'DESC']],
          include: [{ model: User, attributes: ['name'] }],
        },
      ],
    });

    if (!product) {
      return res.status(404).render('errors/404', { title: 'Product Not Found' });
    }

    const relatedProducts = await Product.findAll({
      where: {
        categoryId: product.categoryId,
        id: { [Op.ne]: product.id },
        isActive: true,
      },
      include: [{ model: ProductImage, as: 'images', where: { isPrimary: true }, required: false }],
      limit: 4,
    });

    const avgRating = await Review.findOne({
      attributes: [[require('sequelize').fn('AVG', require('sequelize').col('rating')), 'avgRating']],
      where: { productId: product.id, isApproved: true },
    });

    res.render('product-detail', {
      title: product.name,
      product: product.toJSON(),
      relatedProducts,
      avgRating: avgRating ? parseFloat(avgRating.dataValues.avgRating || 0).toFixed(1) : 0,
      currencySymbol: appConfig.currencySymbol,
    });
  } catch (error) {
    console.error('Product detail error:', error);
    res.status(404).render('errors/404', { title: 'Product Not Found' });
  }
});

// CMS Pages
router.get('/page/:slug', async (req, res) => {
  try {
    const page = await Page.findOne({ where: { slug: req.params.slug, isPublished: true } });
    if (!page) return res.status(404).render('errors/404', { title: 'Page Not Found' });
    res.render('page', { title: page.title, page });
  } catch (error) {
    console.error('Page error:', error);
    res.status(404).render('errors/404', { title: 'Page Not Found' });
  }
});

module.exports = router;
