const { UserDiscounts, Discounts, ListingDiscounts } = require('../../../models');

exports.createDiscount = async (req, res, next) => {
  try {
    const { code } = req.body;
    const { userId } = req;

    let is_global = true;
    let discount = await Discounts.findOne({
      where: {
        code: code,
      },
    });

    if (!discount) {
      is_global = false;
      discount = await ListingDiscounts.findOne({
        where: {
          code: code,
        },
      });
    }

    if (!discount) {
      return res.status(404).json({
        success: false,
        message: 'Discount not found',
      });
    }

    const discountKey = is_global ? 'discount_id' : 'listing_discount_id';

    const userDiscount = await UserDiscounts.findOne({
      where: {
        customer_id: userId,
        [discountKey]: discount.id,
        status: 'active',
      },
    });

    if (userDiscount) {
      return res.status(400).json({
        success: false,
        message: 'Discount already applied',
      });
    }

    await UserDiscounts.create({
      customer_id: userId,
      [discountKey]: discount.id,
    });

    return res.status(201).json({
      success: true,
      message: 'Discount applied successfully',
    });
  } catch (error) {
    next(error);
  }
};

exports.getMyDiscounts = async (req, res, next) => {
  try {
    const { userId } = req;
    const discounts = await UserDiscounts.findAll({
      where: {
        customer_id: userId,
      },
      attributes: {
        exclude: ['customer_id', 'id', 'discount_id', 'listing_discount_id'],
      },
      include: [
        {
          model: Discounts,
          as: 'global_discount',
          attributes: {
            exclude: ['id'],
          },
        },
        {
          model: ListingDiscounts,
          as: 'listing_discount',
          attributes: {
            exclude: ['id'],
          },
        },
      ],
    });

    return res.status(200).json({
      success: true,
      data: discounts,
    });
  } catch (error) {
    next(error);
  }
};
