const packageDbService = require("../services/packagesDbService");
const packageCategoryDbService = require("../services/packageCategoryDbService");
const addPackage = async (req, res) => {
  try {
    const { Title, Intro, PackageCategory_idPackageCategory, NoDays } =
      req.body;

    const images = req.files.map((file) => ({
      filename: file.filename,
    }));

    const add = await packageDbService.addPackage(
      Title,
      Intro,
      PackageCategory_idPackageCategory,
      NoDays
    );
    const insertedId = add.insertId;

    const items = JSON.parse(req.body.items);

    if (items.length > 0) {
      await Promise.all(
        items.map(async (item) => {
          await packageDbService.addPackageHasItems(
            item.Item_Title,
            insertedId
          );
        })
      );
    }

    await packageDbService.addPackageHasImages(images, insertedId);

    res
      .status(201)
      .json({ success: true, message: "package adding completed!" });
  } catch (err) {
    console.log(err);
    res
      .status(500)
      .json({ message: "Something went wrong when adding package!" });
  }
};

const getAllPackages = async (req, res) => {
  try {
    const data = await packageDbService.getAllPackages();
    const baseURL = `${req.protocol}://${req.get("host")}/package-upload/`;

    const data2 = await Promise.all(
      data.map(async (item) => {
        const ImagesRaw =
          await packageCategoryDbService.getPackageImagesByPackageId(
            item.idPackage
          );

        const Images = ImagesRaw.map((img) => `${baseURL}${img.Image}`);
        const getAllItems =
          await packageDbService.getPackageItemDetailsByPackageId(
            item.idPackage
          );
        return {
          ...item,
          Images,
          experiences: getAllItems,
        };
      })
    );
    res.status(200).json(data2);
  } catch (err) {
    console.log(err);
    res
      .status(500)
      .json({ message: "Something went wrong when fetching package!" });
  }
};

const getPackageById = async (req, res) => {
  try {
    const { idPackage } = req.params;
    const data = await packageDbService.getPackageById(idPackage);
    const baseURL = `${req.protocol}://${req.get("host")}/package-upload/`;

    const data2 = await Promise.all(
      data.map(async (item) => {
        const items = await packageDbService.getPackageItemDetailsByPackageId(
          item.idPackage
        );
        const Img_url = baseURL + item.Image;
        return {
          ...item,
          Img_url,
          items,
        };
      })
    );
    res.status(200).json(data2);
  } catch (err) {
    console.log(err);
    res
      .status(500)
      .json({ message: "Something went wrong when fetching package!" });
  }
};

const deletePackage = async (req, res) => {
  try {
    const { idPackage } = req.params;
    await packageDbService.deletePackage(idPackage);
    res.status(200).json({ success: true, message: "Deletion completed!" });
  } catch (err) {
    console.log(err);
    res
      .status(500)
      .json({ message: "Something went wrong when fetching package!" });
  }
};

const updatePackage = async (req, res) => {
  try {
    const { idPackage } = req.params;
    const { Title, Intro, NoDays, items: itemsString } = req.body;
    const items = JSON.parse(itemsString);

    // Handle image upload if present
    const images =
      req.files?.map((file) => ({
        filename: file.filename,
      })) || [];

    console.log("ammt imges : ", images);

    // First update the package basic info
    if (images.length > 0) {
      await packageDbService.deletePackageImagesByPackageId(idPackage);
      await packageDbService.addPackageHasImages(images[0].filename, idPackage);
      await packageDbService.updatePackageWithOutImage(
        idPackage,
        Title,
        Intro,
        NoDays
      );
    } else {
      await packageDbService.updatePackageWithOutImage(
        idPackage,
        Title,
        Intro,
        NoDays
      );
    }

    // Delete existing package items
    await packageDbService.deletePackagesItemsByPackageId(idPackage);

    // Add new items with translations
    if (items.length > 0) {
      await Promise.all(
        items.map(async (item) => {
          await packageDbService.addPackageHasItems(item.Item_Title, idPackage);
        })
      );
    }

    // Handle additional images if any
    if (images.length > 1) {
      // Delete existing images (optional - you might want to keep them)
      await packageDbService.deletePackageImagesByPackageId(idPackage);
      // Add new images (skip first image which is the main image)
      await packageDbService.addPackageHasImages(images.slice(1), idPackage);
    }

    res.status(200).json({
      success: true,
      message: "Package updated successfully!",
    });
  } catch (err) {
    console.log(err);
    res.status(500).json({
      message: "Something went wrong when updating package!",
    });
  }
};

const changePackageStatus = async (req, res) => {
  try {
    const { idPackage } = req.params;
    await packageDbService.changePackageStatus(idPackage);
    res.status(201).json({ success: true, message: "Updating completed!" });
  } catch (err) {
    console.log(err);
    res
      .status(500)
      .json({ message: "Something went wrong when updating package status!" });
  }
};

const packageActiveFetch = async (req, res) => {
  try {
    const data = await packageDbService.getAllPackagesActive();

    const baseURL = `${req.protocol}://${req.get("host")}/package-upload/`;

    const data2 = await Promise.all(
      data.map(async (item) => {
        const ImagesRaw =
          await packageCategoryDbService.getPackageImagesByPackageId(
            item.idPackage
          );

        const Images = ImagesRaw.map((img) => `${baseURL}${img.Image}`);
        const getAllItems =
          await packageDbService.getPackageItemDetailsByPackageIdByLang(
            item.idPackage
          );
        return {
          ...item,
          Images,
          experiences: getAllItems,
        };
      })
    );
    res.status(200).json(data2);
  } catch (err) {
    console.log(err);
    res
      .status(500)
      .json({ message: "Something went wrong when fetching package!" });
  }
};

const packageActiveFetchByCategoryId = async (req, res) => {
  try {
    const { PackageCategory_idPackageCategory, lang } = req.params;
    const data =
      await packageCategoryDbService.getAllPackagesByPackageCategoryIdByLang(
        PackageCategory_idPackageCategory,
        lang
      );

    const baseURL = `${req.protocol}://${req.get("host")}/package-upload/`;

    const data2 = await Promise.all(
      data.map(async (item) => {
        const ImagesRaw =
          await packageCategoryDbService.getPackageImagesByPackageId(
            item.idPackage
          );

        const Images = ImagesRaw.map((img) => `${baseURL}${img.Image}`);
        const getAllItems =
          await packageDbService.getPackageItemDetailsByPackageIdByLang(
            item.idPackage,
            lang
          );
        return {
          ...item,
          Images,
          experiences: getAllItems,
        };
      })
    );
    res.status(200).json(data2);
  } catch (err) {
    console.log(err);
    res
      .status(500)
      .json({ message: "Something went wrong when fetching package!" });
  }
};

const getActivePackagesByNoDays = async (req, res) => {
  try {
    const { NoDays, lang } = req.params;
    const data = await packageCategoryDbService.getActivePackagesByNoDaysByLang(
      NoDays,
      lang
    );

    const baseURL = `${req.protocol}://${req.get("host")}/package-upload/`;

    const data2 = await Promise.all(
      data.map(async (item) => {
        const ImagesRaw =
          await packageCategoryDbService.getPackageImagesByPackageId(
            item.idPackage
          );

        const Images = ImagesRaw.map((img) => `${baseURL}${img.Image}`);
        const getAllItems =
          await packageDbService.getPackageItemDetailsByPackageIdByLang(
            item.idPackage,
            lang
          );
        return {
          ...item,
          Images,
          experiences: getAllItems,
        };
      })
    );
    res.status(200).json(data2);
  } catch (err) {
    console.log(err);
    res
      .status(500)
      .json({ message: "Something went wrong when fetching package!" });
  }
};

module.exports = {
  addPackage,
  getAllPackages,
  getPackageById,
  deletePackage,
  updatePackage,
  changePackageStatus,
  packageActiveFetch,
  packageActiveFetchByCategoryId,
  getActivePackagesByNoDays,
};
