const express = require('express');
const router = express.Router();
const { isAuthenticated } = require('../middleware/auth');
const { User, Order, Wishlist, Product, ProductImage, Review } = require('../models');
const OrderService = require('../services/OrderService');

// Account dashboard
router.get('/', isAuthenticated, async (req, res) => {
  try {
    const user = await User.findByPk(req.session.user.id);
    const recentOrders = await Order.findAll({
      where: { userId: user.id },
      order: [['createdAt', 'DESC']],
      limit: 5,
    });
    res.render('customer/dashboard', { title: 'My Account', user, recentOrders });
  } catch (error) {
    req.flash('error', 'Error loading account.');
    res.redirect('/');
  }
});

// Profile
router.get('/profile', isAuthenticated, async (req, res) => {
  const user = await User.findByPk(req.session.user.id);
  res.render('customer/profile', { title: 'My Profile', user });
});

router.post('/profile', isAuthenticated, async (req, res) => {
  try {
    const { name, phone, address, city, state, pincode } = req.body;
    await User.update(
      { name, phone, address, city, state, pincode },
      { where: { id: req.session.user.id } }
    );
    req.session.user.name = name;
    req.flash('success', 'Profile updated successfully.');
    res.redirect('/account/profile');
  } catch (error) {
    req.flash('error', 'Error updating profile.');
    res.redirect('/account/profile');
  }
});

// Order history
router.get('/orders', isAuthenticated, async (req, res) => {
  try {
    const page = parseInt(req.query.page) || 1;
    const data = await OrderService.getUserOrders(req.session.user.id, page);
    res.render('customer/orders', { title: 'My Orders', ...data });
  } catch (error) {
    req.flash('error', 'Error loading orders.');
    res.redirect('/account');
  }
});

// Order detail
router.get('/orders/:id', isAuthenticated, async (req, res) => {
  try {
    const order = await OrderService.getOrderDetail(req.params.id, req.session.user.id);
    if (!order) {
      req.flash('error', 'Order not found.');
      return res.redirect('/account/orders');
    }
    res.render('customer/order-detail', { title: `Order #${order.orderNumber}`, order });
  } catch (error) {
    req.flash('error', 'Error loading order.');
    res.redirect('/account/orders');
  }
});

// Wishlist
router.get('/wishlist', isAuthenticated, async (req, res) => {
  try {
    const wishlist = await Wishlist.findAll({
      where: { userId: req.session.user.id },
      include: [{
        model: Product,
        include: [{ model: ProductImage, as: 'images', where: { isPrimary: true }, required: false }],
      }],
      order: [['createdAt', 'DESC']],
    });
    res.render('customer/wishlist', { title: 'My Wishlist', wishlist });
  } catch (error) {
    req.flash('error', 'Error loading wishlist.');
    res.redirect('/account');
  }
});

// Add to wishlist
router.post('/wishlist/add', isAuthenticated, async (req, res) => {
  try {
    const { productId } = req.body;
    const existing = await Wishlist.findOne({
      where: { userId: req.session.user.id, productId },
    });
    if (!existing) {
      await Wishlist.create({ userId: req.session.user.id, productId });
    }
    res.json({ success: true });
  } catch (error) {
    res.json({ success: false, message: 'Error adding to wishlist.' });
  }
});

// Remove from wishlist
router.post('/wishlist/remove', isAuthenticated, async (req, res) => {
  try {
    await Wishlist.destroy({
      where: { userId: req.session.user.id, productId: req.body.productId },
    });
    res.json({ success: true });
  } catch (error) {
    res.json({ success: false });
  }
});

// Submit review
router.post('/review', isAuthenticated, async (req, res) => {
  try {
    const { productId, rating, comment } = req.body;
    const existing = await Review.findOne({
      where: { userId: req.session.user.id, productId },
    });
    if (existing) {
      req.flash('error', 'You have already reviewed this product.');
      return res.redirect('back');
    }
    await Review.create({
      productId,
      userId: req.session.user.id,
      rating: parseInt(rating),
      comment,
    });
    req.flash('success', 'Review submitted and pending approval.');
    res.redirect('back');
  } catch (error) {
    req.flash('error', 'Error submitting review.');
    res.redirect('back');
  }
});

module.exports = router;
