const httpStatus = require("http-status");
require("dotenv").config();
const { Site, Plot } = require("../models");
const jwt = require("jsonwebtoken");
const bcrypt = require("bcrypt");

const addSite = async (req, res) => {
  try {
    console.log(req.files.site_map);
    const siteMap = req.files["site_map"] ? req.files["site_map"][0].path : "";
    const siteBrochure = req.files["site_brochure"]
      ? req.files["site_brochure"][0].path
      : "";
    req.body.site_map = siteMap;
    req.body.site_brochure = siteBrochure;
    req.body.is_active = 1;

    const site = new Site(req.body);
    const savedSite = await site.save();

    const plots = Array.from({ length: req.body.total_plot }).map(
      (_, index) => ({
        plot_number: index + 1,
        plot_area: "",
        plot_type: "Residential",
        amount: req.body.residential,
        total: req.body.residential,
        site_id: savedSite.dataValues.id,
        is_active: 1,
      })
    );

    // Save all plots in one go using bulkCreate
    await Plot.bulkCreate(plots);

    res
      .status(httpStatus.CREATED)
      .json({ msg: "Project Added Successfully", site: savedSite });
  } catch (error) {
    console.error("Error saving project data:", error);
    res.status(httpStatus.INTERNAL_SERVER_ERROR).json({ msg: "Server error" });
  }
};

const getSite = async (req, res) => {
  try {
    const spkg = await Site.findAll({
      where: { is_delete: false },
    });
    await Promise.all(
      spkg.map(async (obj) => {
        // Fetch events for each event id
        const plots = await Plot.findAll({
          where: { site_id: obj.dataValues.id, is_delete: false },
        });

        obj.dataValues.plots = plots;
      })
    );
    res
      .status(httpStatus.OK)
      .json({ msg: "Project Fetch Successfully", site: spkg });
  } catch (error) {
    console.error("Error saving project data:", error);
    res.status(httpStatus.INTERNAL_SERVER_ERROR).json({ msg: "Server error" });
  }
};

const getSiteById = async (req, res) => {
  try {
    const spkg = await Site.findOne({
      where: { is_delete: false, id: req.params.id },
    });

    if (!spkg) {
      return res
        .status(httpStatus.BAD_REQUEST)
        .json({ msg: "Project not found" });
    }
    const plots = await Plot.findAll({
      where: { site_id: spkg.dataValues.id, is_delete: false, is_active: true },
    });

    spkg.dataValues.plots = plots;
    res
      .status(httpStatus.OK)
      .json({ msg: "Project Fetch Successfully", site: spkg });
  } catch (error) {
    console.error("Error saving project data:", error);
    res.status(httpStatus.INTERNAL_SERVER_ERROR).json({ msg: "Server error" });
  }
};

const updateSite = async (req, res) => {
  try {
    const exist = await Site.findOne({
      where: { is_delete: false, id: req.params.id },
    });
    if (!exist) {
      return res
        .status(httpStatus.BAD_REQUEST)
        .json({ msg: "Project not found" });
    }

    const siteMap = req.files["site_map"]
      ? req.files["site_map"][0].path
      : exist.siteMap;
    const siteBrochure = req.files["site_brochure"]
      ? req.files["site_brochure"][0].path
      : exist.siteBrochure;
    req.body.site_map = siteMap;
    req.body.site_brochure = siteBrochure;
    const site = await Site.update(
      {
        ...req.body,
      },
      { where: { is_delete: false, id: req.params.id } }
    );
    const savedSite = await Site.findOne({
      where: { is_delete: false, id: req.params.id },
    });
    res
      .status(httpStatus.OK)
      .json({ msg: "Project Update Successfully", site: savedSite });
  } catch (error) {
    res.status(httpStatus.INTERNAL_SERVER_ERROR).json({ msg: "Server error" });
  }
};

const deleteSite = async (req, res) => {
  try {
    const exist = await Site.findOne({
      where: { is_delete: false, id: req.params.id },
    });
    if (!exist) {
      return res
        .status(httpStatus.BAD_REQUEST)
        .json({ msg: "Project not found" });
    }
    const site = await Site.update(
      {
        is_delete: true,
      },
      { where: { is_delete: false, id: req.params.id } }
    );

    await Plot.update(
      { is_delete: true },
      { where: { site_id: req.params.id } }
    );

    res.status(httpStatus.OK).json({ msg: "Project Delete Successfully" });
  } catch (error) {
    res.status(httpStatus.INTERNAL_SERVER_ERROR).json({ msg: "Server error" });
  }
};

const activateSite = async (req, res) => {
  try {
    const exist = await Site.findOne({
      where: { is_delete: false, id: req.params.id },
    });
    if (!exist) {
      return res
        .status(httpStatus.BAD_REQUEST)
        .json({ msg: "Project not found" });
    }
    const site = await Site.update(
      {
        is_active: !exist.dataValues.is_active,
      },
      { where: { is_delete: false, id: req.params.id } }
    );

    await Plot.update(
      { is_active : !exist.dataValues.is_active },
      { where: { is_delete: false, site_id: req.params.id } }
    );

    res.status(httpStatus.OK).json({ msg: "Project Update Successfully" });
  } catch (error) {
    res.status(httpStatus.INTERNAL_SERVER_ERROR).json({ msg: "Server error" });
  }
};

const addMorePlot = async (req, res) => {
  try {
    const exist = await Site.findOne({
      where: { is_delete: false, id: req.params.id },
    });
    if (!exist) {
      return res
        .status(httpStatus.BAD_REQUEST)
        .json({ msg: "Project not found" });
    }
    const exist_tot_plot = exist.dataValues.total_plot;
    console.log(
      exist_tot_plot,
      req.body.total_plot,
      exist_tot_plot + req.body.total_plot
    );
    await Site.update(
      {
        total_plot: exist_tot_plot + req.body.total_plot,
      },
      { where: { id: req.params.id } }
    );

    const plots = Array.from({ length: req.body.total_plot }).map(
      (_, index) => ({
        plot_number: exist_tot_plot + index + 1,
        plot_area: "",
        plot_type: "Residential",
        amount: exist.dataValues.residential,
        total: exist.dataValues.residential,
        site_id: exist.dataValues.id,
        is_active: 1,
      })
    );

    // Save all plots in one go using bulkCreate
    await Plot.bulkCreate(plots);

    res.status(httpStatus.CREATED).json({ msg: "Add more plot Successfully" });
  } catch (error) {
    console.error("Error saving project data:", error);
    res.status(httpStatus.INTERNAL_SERVER_ERROR).json({ msg: "Server error" });
  }
};

module.exports = {
  addSite,
  getSite,
  getSiteById,
  updateSite,
  deleteSite,
  activateSite,
  addMorePlot,
};
