const packageCategoryDbService = require("../services/packageCategoryDbService");
const packageDbService = require("../services/packagesDbService");
const add = async (req, res) => {
  try {
    const { title, description } = req.body;
    const Image = req.files?.Image?.[0]?.filename;
    const Image2 = req.files?.Image2?.[0]?.filename;

    await packageCategoryDbService.add(title, description, Image, Image2);
    res.status(201).json({ message: "Adding completed", success: true });
  } catch (err) {
    console.log(err);
    res.status(500).json({
      message: "Something went wrong when adding package category!",
      error: err.message,
    });
  }
};

// UPDATE
const update = async (req, res) => {
  try {
    const { id } = req.params;
    const { title, description } = req.body;

    const Image = req.files?.Image?.[0]?.filename;
    const Image2 = req.files?.Image2?.[0]?.filename;

    // Case 1: Both images provided
    if (Image && Image2) {
      await packageCategoryDbService.update(
        id,
        title,
        description,
        Image,
        Image2
      );
    }

    // Case 2: Only Image1 provided
    else if (Image && !Image2) {
      await packageCategoryDbService.updateOnlyImage1(
        id,
        title,
        description,
        Image
      );
    }

    // Case 3: Only Image2 provided
    else if (!Image && Image2) {
      await packageCategoryDbService.updateOnlyImage2(
        id,
        title,
        description,
        Image2
      );
    }

    // Case 4: No images provided
    else {
      await packageCategoryDbService.updateWithoutImage(id, title, description);
    }

    res.status(200).json({ message: "Update completed", success: true });
  } catch (err) {
    res.status(500).json({
      message: "Something went wrong when updating package category!",
      error: err.message,
    });
  }
};

// DELETE
const remove = async (req, res) => {
  try {
    const { id } = req.params;
    await packageCategoryDbService.remove(id);
    res.status(200).json({ message: "Delete completed", success: true });
  } catch (err) {
    res.status(500).json({
      message: "Something went wrong when deleting package category!",
      error: err.message,
    });
  }
};

// GET BY ID
const getById = async (req, res) => {
  try {
    const baseURL = `${req.protocol}://${req.get("host")}/package-upload/`;
    const baseURL2 = `${req.protocol}://${req.get(
      "host"
    )}/package-category-upload/`;

    const baseURL3 = `${req.protocol}://${req.get(
      "host"
    )}/package-category-hero/`;
    const { id } = req.params;
    const data = await packageCategoryDbService.getById(id);
    const result = data.map((item) => ({
      ...item,
      pc_url: baseURL2 + item.Image,
      hero_url: baseURL3 + item.Hero,
    }));

    const data2 = await Promise.all(
      result.map(async (item) => {
        const packages =
          await packageCategoryDbService.getAllPackagesByPackageCategoryId(
            item.idPackageCategory
          );
        const data3 = await Promise.all(
          packages.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,
            };
          })
        );
        return {
          ...item,
          packages: data3,
        };
      })
    );

    res.status(200).json(data2);
  } catch (err) {
    res.status(500).json({
      message: "Something went wrong when fetching package category!",
      error: err.message,
    });
  }
};

// GET ALL
const getAll = async (req, res) => {
  try {
    const baseURL = `${req.protocol}://${req.get("host")}/package-upload/`;
    const baseURL2 = `${req.protocol}://${req.get(
      "host"
    )}/package-category-upload/`;
    const baseURL3 = `${req.protocol}://${req.get(
      "host"
    )}/package-category-hero/`;

    const data = await packageCategoryDbService.getAll();
    const result = data.map((item) => ({
      ...item,
      pc_url: baseURL2 + item.Image,
      hero_url: baseURL3 + item.Hero,
    }));

    const data2 = await Promise.all(
      result.map(async (item) => {
        const packages =
          await packageCategoryDbService.getAllPackagesByPackageCategoryId(
            item.idPackageCategory
          );
        const data3 = await Promise.all(
          packages.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,
            };
          })
        );
        return {
          ...item,
          packages: data3,
        };
      })
    );

    res.status(200).json(data2);
  } catch (err) {
    res.status(500).json({
      message: "Something went wrong when fetching package categories!",
      error: err.message,
    });
  }
};

const getPackageCategoryByLang = async (req, res) => {
  try {
    const { lang } = req.params;
    const baseURL = `${req.protocol}://${req.get("host")}/package-upload/`;
    const baseURL2 = `${req.protocol}://${req.get(
      "host"
    )}/package-category-upload/`;
    const baseURL3 = `${req.protocol}://${req.get(
      "host"
    )}/package-category-hero/`;
    const data = await packageCategoryDbService.getPackageCategoryByLang(lang);
    const result = data.map((item) => ({
      ...item,
      pc_url: baseURL2 + item.Image,
      hero_url: baseURL3 + item.Hero,
    }));

    const data2 = await Promise.all(
      result.map(async (item) => {
        const packages =
          await packageCategoryDbService.getAllPackagesByPackageCategoryIdByLang(
            item.idPackageCategory,
            lang
          );
        const data3 = await Promise.all(
          packages.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,
            };
          })
        );
        return {
          ...item,
          packages: data3,
        };
      })
    );

    res.status(200).json(data2);
  } catch (err) {
    res.status(500).json({
      message: "Something went wrong when fetching package categories!",
      error: err.message,
    });
  }
};

const getPackageCategoryIDByLang = async (req, res) => {
  try {
    const { lang, idPackageCategory } = req.params;
    const baseURL = `${req.protocol}://${req.get("host")}/package-upload/`;
    const baseURL2 = `${req.protocol}://${req.get(
      "host"
    )}/package-category-upload/`;

    const baseURL3 = `${req.protocol}://${req.get(
      "host"
    )}/package-category-hero/`;

    const data = await packageCategoryDbService.getPackageCategoryByLangID(
      lang,
      idPackageCategory
    );
    const result = data.map((item) => ({
      ...item,
      pc_url: baseURL2 + item.Image,
      hero_url: baseURL3 + item.Hero,
    }));

    const data2 = await Promise.all(
      result.map(async (item) => {
        const packages =
          await packageCategoryDbService.getAllPackagesByPackageCategoryIdByLang(
            item.idPackageCategory,
            lang
          );
        const data3 = await Promise.all(
          packages.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,
            };
          })
        );
        return {
          ...item,
          packages: data3,
        };
      })
    );

    res.status(200).json(data2);
  } catch (err) {
    res.status(500).json({
      message: "Something went wrong when fetching package categories!",
      error: err.message,
    });
  }
};

module.exports = {
  add,
  update,
  remove,
  getById,
  getAll,
  getPackageCategoryByLang,
  getPackageCategoryIDByLang,
};
