import {Goods, GoodsAttributes, GoodsFavourites, sequelize} from "../../models/index";
import GoodsNotFound from '../../utils/customErrors/goodsNotFound';
import {typesFilter} from "../../utils/constans/goods";

const {Op} = sequelize;

module.exports.getGoodsByGroupController = async (req, res, next) => {

  let goods = await Goods.findAll(req.body.goodsFilter);
  goods = goods.slice(0, +req.query.rows * 4);
  res.send(goods);
};

module.exports.getGoodsByIdController = async (req, res, next) => {
    const simpleGoods = await Goods.findOne({
        where: {
            id: {
                [Op.eq]: req.params.id
            }
        },
        include: [
            {
                model: GoodsAttributes,
                attributes: {
                    exclude: ["createdAt", "updatedAt"]
                }
            }
        ],
        attributes: {
            exclude: ["createdAt", "updatedAt"]
        },
        order: [
            ['GoodsAttributes', 'id', 'asc']
        ]
    });

    res.send(simpleGoods);
};

module.exports.getFavouriteGoodsController = (req, res, next) => {
    res.send(req.body.favouriteGoodsArray);
};

module.exports.appendFavouriteGoodsController = async (req, res, next) => {
    res.send(req.body.favouriteGoodsArray);
};

module.exports.deleteFavouriteGoodsController = (req, res, next) => {
    res.send(req.body.favouriteGoodsArray);
};

module.exports.appendOrdersController = (req, res, next) => {
    res.sendStatus(200);
};

module.exports.dynamicSearchGoodsController = async (req, res, next) => {
  try {
      if(req.params.searchString) {
          const goods = await Goods.findAll({
              where: {
                  goodsName: {
                      [Op.like]: '%' + req.params.searchString + '%'
                  }
              },
              attributes: {
                  exclude: ['createdAt', 'updatedAt', 'isSale', 'volumesArray']
              },
              include: {
                  model: GoodsAttributes,
                  attributes: {
                      exclude: ['createdAt', 'updatedAt', 'goodsId']
                  }
              },
              order: [['GoodsAttributes', 'id', 'asc']],
              limit: 20
          });
          res.send(goods);
      }else {
          res.send([]);
      }

  }catch (e) {
      next(e);
  }
};

module.exports.deletePictureController = async (req, res, next) => {
    try {
            const goods = await Goods.findOne({
                where: {
                    id: req.body.goodId
                },
                attributes: {
                    exclude: ['createdAt', 'updatedAt', 'isSale', 'volumesArray']
                },
                include: {
                    model: GoodsAttributes,
                    attributes: {
                        exclude: ['createdAt', 'updatedAt', 'goodsId']
                    }
                },
                order: [['GoodsAttributes', 'id', 'asc']]
            });
            res.send(goods);

    }catch (e) {
        next(e);
    }
};

module.exports.updateGoodsController = async (req, res, next) => {
    try {
        const goods = await Goods.findOne({
            where: {
                id: req.body.goodId
            },
            attributes: {
                exclude: ['createdAt', 'updatedAt', 'isSale', 'volumesArray']
            },
            include: {
                model: GoodsAttributes,
                attributes: {
                    exclude: ['createdAt', 'updatedAt', 'goodsId']
                }
            },
            order: [['GoodsAttributes', 'id', 'asc']]
        });
        res.send(goods);

    }catch (e) {
        next(new GoodsNotFound());
    }
};

module.exports.deleteSingleGoodsController = (req, res, next) => {
    res.send({});
};

module.exports.appendPictureForAttributeController = async (req, res, next) => {
    try {
        const goods = await Goods.findOne({
            where: {
                id: req.body.goodId
            },
            attributes: {
                exclude: ['createdAt', 'updatedAt', 'isSale', 'volumesArray']
            },
            include: {
                model: GoodsAttributes,
                attributes: {
                    exclude: ['createdAt', 'updatedAt', 'goodsId']
                },
            },
            order: [['GoodsAttributes', 'id', 'asc']]

        });
        res.send(goods);

    }catch (e) {
        next(new GoodsNotFound());
    }
};

module.exports.updateGoodsAttributesController = async (req, res, next) => {
    try {
        const goods = await Goods.findOne({
            where: {
                id: req.body.goodId
            },
            attributes: {
                exclude: ['createdAt', 'updatedAt', 'isSale', 'volumesArray']
            },
            include: {
                model: GoodsAttributes,
                attributes: {
                    exclude: ['createdAt', 'updatedAt', 'goodsId']
                },
            },
            order: [['GoodsAttributes', 'id', 'asc']]

        });
        res.send(goods);

    }catch (e) {
        next(new GoodsNotFound());
    }
};

module.exports.deleteGoodsAttributesController = async (req, res, next) => {
    try {
        const goods = await Goods.findOne({
            where: {
                id: req.body.goodId
            },
            attributes: {
                exclude: ['createdAt', 'updatedAt', 'isSale', 'volumesArray']
            },
            include: {
                model: GoodsAttributes,
                attributes: {
                    exclude: ['createdAt', 'updatedAt', 'goodsId']
                },
            },
            order: [['GoodsAttributes', 'id', 'asc']]

        });
        res.send(goods);

    }catch (e) {
        next(new GoodsNotFound());
    }
};

module.exports.filterTypesCounterController = async (req, res, next) => {
    const countTypesForFilter = {};

    console.log(req.params.id);

    const resultGoodsFragrance = await sequelize.query(`
        SELECT DISTINCT "goodsMadeIn", (
          SELECT count(*)
          FROM "Goods"
          WHERE filterType."goodsMadeIn" = "Goods"."goodsMadeIn"
          AND "Goods"."goodsGroupId" IN (${req.params.id})
          )
        FROM "Goods" AS filterType
        WHERE "goodsGroupId" IN (${req.params.id})
    `);

    const resultGoodsGender = await sequelize.query(`
        SELECT DISTINCT "goodsGender", (
          SELECT count(*)
          from "Goods"
          where filterType."goodsGender" = "Goods"."goodsGender"
          AND "Goods"."goodsGroupId" IN (${req.params.id})
          )
        FROM "Goods" AS filterType
        WHERE "goodsGroupId" IN (${req.params.id})
    `);

    const resultGoodsBrandId = await sequelize.query(`
        SELECT DISTINCT "goodsBrandId", (
          SELECT count(*)
          FROM "Goods"
          WHERE filterType."goodsBrandId" = "Goods"."goodsBrandId"
          AND "Goods"."goodsGroupId" IN (${req.params.id})
          )
        FROM "Goods" AS filterType
        WHERE "goodsGroupId" IN (${req.params.id})
    `);

    const resultVolumes = await sequelize.query(`
        SELECT DISTINCT "valueAttribute", "nameAttribute", (
          SELECT count(*)
          FROM "Goods"
          WHERE filterType."valueAttribute" = ANY ("Goods"."volumesArray")
          AND "Goods"."goodsGroupId" IN (${req.params.id})
        )
        FROM "GoodsAttributes" AS filterType
    `);

    Object.assign(countTypesForFilter, {
        goodsMadeIn: resultGoodsFragrance[0],
        goodsGender: resultGoodsGender[0],
        goodsBrandId: resultGoodsBrandId[0],
        goodsVolumes: resultVolumes[0].filter(elem => elem.count > 0)
    });

    res.send(countTypesForFilter);

};

module.exports.orderBySearchStringController = (req, res, next) => {

};
