const ProductMenu = require("../models/ProductMenu");
const Products = require("../models/Products");
const jwt = require("jsonwebtoken");
const errorHandler = require("../util/errorHandler");
const multer = require("multer");
const SellersCompany = require("../models/SellersCompany");
// Create a new product

exports.createProduct = (req, res, next) => {
  const { data } = req.body;
  const { product_category, product_size, product_description, status } = data;

  if (!product_category) {
    return errorHandler("ProductMenu ID is missing from the request.", 400);
  }

  if (!req.files || !req.files.productmenuPhoto) {
    return errorHandler("ProductMenu photo is missing from the request.", 500);
  }

  const { productmenuPhoto } = req.files;
  const { uploadproductmenuPhoto } = req.files;

  // Check if the product menu already exists
  ProductMenu.findOne({
    where: {
      product_menu: product_category,
    },
  })
    .then((existingProductMenu) => {
      if (existingProductMenu) {
        return errorHandler("ProductMenu ID already exists!", 401);
      }

      // Create the new product menu
      return ProductMenu.create({
        product_menu: product_category,
        description: product_description,
        size_category: product_size,
        photo: productmenuPhoto[0].filename || null,
        upload_photo: uploadproductmenuPhoto[0].filename || null,
        status,
      });
    })
    .then((createdProduct) => {
      const { id, product_menu, size_category, photo, upload_photo, status } = createdProduct;
      const formattedProduct = {
        category_id: id,
        product_category: product_menu,
        product_size: size_category,
        product_description: product_description,
        photo,
        upload_photo,
        status,
      };
      res.status(201).json({ success: true, product: formattedProduct });
    })
    .catch((err) => {
      next(err);
    });
};

exports.updateProductById = (req, res, next) => {
  // Extracting productId from request parameters
  const { productId } = req.params;

  // Extracting data and specific properties from request body
  const { data } = req.body;
  const {
    product_category,
    product_size,
    product_description, // Include product_description field from request body
    status,
  } = data;

  // Extracting productmenuPhoto and uploadproductmenuPhoto from request files
  const { productmenuPhoto } = req.files;
  const { uploadproductmenuPhoto } = req.files;

  // Finding the ProductMenu by ID
  ProductMenu.findOne({
    where: {
      id: productId,
    },
  })
    .then((productmenu) => {
      // Error handling if productmenu not found
      if (!productmenu) {
        return errorHandler("ProductMenu ID does not exist!", 404);
      }

      // Updating productmenu photo if productmenuPhoto exists
      if (productmenuPhoto && productmenuPhoto.length > 0) {
        productmenu.photo = productmenuPhoto[0].filename;
      } else {
        productmenu.photo = null;
      }

      // Updating upload productmenu photo if uploadproductmenuPhoto exists
      if (uploadproductmenuPhoto && uploadproductmenuPhoto.length > 0) {
        productmenu.upload_photo = uploadproductmenuPhoto[0].filename;
      } else {
        productmenu.upload_photo = null;
      }

      // Updating other properties of the productmenu
      productmenu.product_menu = product_category;
      productmenu.size_category = product_size;
      productmenu.description = product_description; // Include description in update
      productmenu.status = status;

      // Saving changes to the ProductMenu
      return productmenu.save();
    })
    .then((updatedProductMenu) => {
      // Sending success response with updated product details
      const { id, product_menu, size_category, photo, upload_photo, status, description } = updatedProductMenu;
      res.status(200).json({
        success: true,
        category_id: id,
        product_category: product_menu,
        product_size: size_category,
        product_description: description, // Include product_description in response
        status,
        productmenuPhoto: photo ? photo : null,
        uploadproductmenuPhoto: upload_photo ? upload_photo : null,
      });
    })
    .catch((err) => {
      // Forwarding error to next middleware
      next(err);
    });
};

exports.getAllProducts = async (req, res) => {
  try {
    // Find all products
    const products = await Products.findAll({
      include: [
        {
          model: SellersCompany,
          as: "seller",
          attributes: ["id", "company_name", "shop_name", "seller_logo"],
        },
        {
          model: ProductMenu,
          as: "menus",
          attributes: ["id", "product_menu", "description", "photo", "status"],
        },
      ],
    });

    // Extract distinct product menus
    const distinctMenus = {};
    products.forEach((product) => {
      const menuId = product.menus ? product.menus.id : null;
      if (menuId && !distinctMenus[menuId]) {
        distinctMenus[menuId] = {
          category_id: menuId,
          product_category: product.menus.product_menu,
          description: product.menus.description,
          photo: `https://buildhub.ph/img/${product.menus.photo}`,
          status: product.menus.status,
        };
      }
    });

    // Convert distinctMenus object to array
    const distinctMenusArray = Object.values(distinctMenus);

    res.status(200).json({ products: distinctMenusArray });
  } catch (error) {
    console.error(error);
    res.status(500).json({ error: "Internal Server Error" });
  }
};

exports.getProductById = async (req, res) => {
  const { product_category } = req.params;

  try {
    // Find all products belonging to the specific category
    const products = await Products.findAll({
      where: {
        menu_id: product_category,
      },
      include: [
        {
          model: SellersCompany,
          as: "seller",
          attributes: ["id", "company_name", "shop_name", "seller_logo"],
        },
        {
          model: ProductMenu,
          as: "menus",
          attributes: ["id", "product_menu", "description"], // Adjust attributes as needed
        },
      ],
    });

    // Map the products array to include all properties
    const mappedProducts = products.map((product) => ({
      category_ID: product.menus.id,
      product_Category: product.menus.product_menu,
      product_description: product.menus.description, // Include description in response
      product_size: product.size_category,
      photos: `https://buildhub.ph/img${product.photo}`,
      upload_photos: `https://buildhub.ph/img/${product.upload_photo}`,
      status: product.status,
      seller: {
        seller_Id: product.seller.id,
        seller_name: product.seller.company_name,
        seller_logo: `https://buildhub.ph/img/seller/${product.seller.seller_logo}`,
        banner: product.seller.seller_banner_image
          ? `https://buildhub.ph/img/seller/${product.seller.seller_banner_image}`
          : null,
      },
    }));

    res.status(200).json({ "Product Category by ID": mappedProducts });
  } catch (error) {
    console.error(error);
    res.status(500).json({ error: "Internal Server Error" });
  }
};

exports.getProductByMenu = async (req, res) => {
  const { productMenu } = req.params;

  try {
    const product = await ProductMenu.findOne({
      where: { product_menu: productMenu },
    });

    if (!product) {
      return res.status(404).json({ error: "Product not found" });
    }

    // Constructing the response directly from the fetched product
    const productResponse = {
      category_id: product.id,
      product_category: product.product_menu,
      product_description: product.description,
      product_size: product.size_category,
      photos: `https://buildhub.ph/img/products/${product.photo}`,
      upload_photos: `https://buildhub.ph/img/products/${product.upload_photo}`,
      status: product.status,
    };

    res.status(200).json(productResponse);
  } catch (error) {
    console.error(error);
    res.status(500).json({ error: "Internal Server Error" });
  }
};

exports.deleteProductById = (req, res) => {
  const { productId } = req.params;

  try {
    const deletedRowCount = ProductMenu.destroy({
      where: {
        id: productId,
      },
    });

    if (deletedRowCount === 0) {
      return res.status(404).json({ error: "Product not found" });
    }

    res.status(204).send();
  } catch (error) {
    console.error(error);
    res.status(500).json({ error: "Internal Server Error" });
  }
};

exports.getAllProductMenu = (req, res, next) => {
  ProductMenu.findAll()
    .then((category) => {
      const categories = category.map((category) => ({
        id: category.id,
        name: category.product_menu,
        description: category.description,
        photo: `https://buildhub.ph/img/products/${category.photo}`,
        status: category.status,
      }));

      return res.status(200).json({ success: true, categories });
    })
    .catch((err) => {
      next(err);
    });
};
