const User = require("../models/User");
const Customer = require("../models/Customer");
const Favorite = require("../models/Favorite");
const Order = require("../models/Order");
const OrderItem = require("../models/Orderitem");
const Product = require("../models/Product");
const ProductItem = require("../models/ProductItem");
const Producers = require("../models/Producers");
const authService = require("../../services/auth.service");
const helperService = require("../../services/helpers.service");
const { includes } = require("lodash");

exports.createFavorite = async (req, res) => {
  var { token, product_id, producer_id } = req.body;
  if (token) {
    authService().verify(token, async (err, data) => {
      if (err) {
        return helperService().unauthorized(res);
      }
      const customer = await Customer.findOne({
        where: {
          user_id: data.id,
        },
      });
      if(product_id){
        var favorite = await Favorite.findOne({
            where: {
              customer_id: customer.id,
              product_id,
            },
          });
          if (favorite) {
            var favoriteUpdate = await Favorite.update(
              { status: 1 },
              {
                where: {
                  customer_id: customer.id,
                  product_id,
                },
              }
            );
    
            return helperService().success( [], "Favorite created successfully", res );
          } else {
            var favoriteCreate = await Favorite.create({
              customer_id: customer.id,
              product_id,
            });
    
            return helperService().success( [], "Favorite created successfully", res );
          }
      }else if(producer_id){
        var favorite = await Favorite.findOne({
            where: {
              customer_id: customer.id,
              producer_id,
            },
          });
          if (favorite) {
            var favoriteUpdate = await Favorite.update(
              { status: 1 },
              {
                where: {
                  customer_id: customer.id,
                  producer_id,
                },
              }
            );
    
            return helperService().success( [], "Favorite created successfully", res );
          } else {
            var favoriteCreate = await Favorite.create({
              customer_id: customer.id,
              producer_id,
            });
            return helperService().success( [], "Favorite created successfully", res );
          }
      }
    });
  } else {
    return helperService().badRequest( [], "Token is required", res );
  }
};
exports.removeFavorite = async (req, res) => {
  var { token, product_id, producer_id } = req.body;
  if (token) {
    authService().verify(token, async (err, data) => {
      if (err) {
        return helperService().unauthorized(res);
      }

      const customer = await Customer.findOne({
        where: {
          user_id: data.id,
        },
      });
      if (product_id) {
        var favorite = await Favorite.findOne({
            where: {
            customer_id: customer.id,
            product_id,
            },
        });
        if (favorite) {
            var favoriteUpdate = await Favorite.update(
            { status: 0 },
            {
                where: {
                    customer_id: customer.id,
                    product_id,
                },
            }
            );
            return helperService().success([], "Favorite remove successfully", res);
        }else{
            return helperService().success([], "No data found", res);
        }
      }else {
        var favorite = await Favorite.findOne({
            where: {
                customer_id: customer.id,
                producer_id,
            },
        });
        if (favorite) {
            var favoriteUpdate = await Favorite.update(
            { status: 0 },
            {
                where: {
                    customer_id: customer.id,
                    producer_id,
                },
            }
            );
            return helperService().success([], "Favorite remove successfully", res);
        }else{
            return helperService().success([], "No data found", res);
        }
      }
    });
  } else {
    return helperService().badRequest(
      [],
      "token is required",
      res
    );
  }
};
exports.favorites = async (req, res) => {
  var { token } = req.query;
  if (token) {
    authService().verify(token, async (err, data) => {
      if (err) {
        return helperService().unauthorized(res);
      }

      const favorite = await Favorite.findAll({
        where: {
          customer_id: data.customer_id,
          status: 1,
        },
        attributes: ["product_id", "producer_id"],
      });
      var favIds = [];
      var proIds = [];
      favorite.forEach((itm) => {
        if(itm.product_id){
            favIds.push(itm.product_id);
        }else if(itm.producer_id){
            proIds.push(itm.producer_id);
        }
      });

      var product = await Product.findAll({
        include:[
            {
                model: ProductItem,
                attributes: ["id","packing_text","price"],
                where:{
                    status: 1
                }
            },
            {
                model:Producers,
                required: true,
                attributes: ["address"],
            }
        ],
        attributes: ["id","name","description","abv","ibu","image","rating"],
        where: {
            id: favIds,
            status: 1
        },
      });
      var producer = await Producers.findAll({
        attributes: ["id", "name", "description", "address", "image", "cover_image"],
        where: {
            id: proIds,
            status: 1
        },
      });
      if (product == null || producer == null) {
        if(product == null){
            var product = []
            return helperService().success([{ product, producer }], "Favorite found", res);
        }else{
            var producer = []
            return helperService().success([{ product, producer }], "Favorite found", res);
        }
      } else if(product == null && producer == null){
        var product = []
        var producer = []
        return helperService().success([{ product, producer }], "No data found", res);
      }else{
        return helperService().success([{ product, producer }], "Favorite found", res);
      }
    });
  } else {
    return helperService().badRequest([], "Token is required", res);
  }
};
exports.history = async (req, res) => {
  var { token, filter } = req.query;
  if (token) {
    authService().verify(token, async (err, data) => {
      if (err) {
        return helperService().unauthorized(res);
      }
      if (filter == "" || filter == undefined || filter == null) {
        return helperService().badRequest([], "Filter is required", res);
      } else {
        if (filter == "recentontop") {
          var history = await Order.findAll({
            where: {
              customer_id: data.customer_id,
            },
            limit: 10,
            order: [["created_at", "DESC"]],
            attributes:['id','createdAt']
          });
          if (history == null) {
            return helperService().success([{ history }], "No data available", res);
          } else {
            return helperService().success( [{ history }], "history found", res );
          }
        }
        if (filter == "oldestontop") {
          var history = await Order.findAll({
            where: {
              customer_id: data.customer_id,
            },
            limit: 10,
            order: [["created_at", "ASC"]],
            attributes:['id','createdAt']
          });
          if (history == null) {
            return helperService().success([{ history }], "No data available", res);
          } else {
            return helperService().success( [{ history }], "history found", res );
          }
        }
      }
    });
  } else {
    return helperService().badRequest([], "Token is required", res);
  }
};
