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

const generateQuotation = async (req, res) => {
  try {
    const quo = new generateQuotations(req.body);
    const quoSave = await quo.save();

    res
      .status(httpStatus.CREATED)
      .json({ msg: "Quotation Generate Successfully", quotation: quoSave });
  } catch (error) {
    console.error("Error saving quotation data:", error);
    res.status(httpStatus.INTERNAL_SERVER_ERROR).json({ msg: "Server error" });
  }
};

const getQuotation = async (req, res) => {
  try {
    const spkg = await generateQuotations.findAll();
    await Promise.all(
      spkg.map(async (obj) => {
        // Fetch events for each event id
        const plot = await Plot.findOne({
          where: { id: obj.dataValues.plot_id },
        });

        const site = await Site.findOne({
          where: { id: plot.dataValues.site_id },
        });

        const broker = await Broker.findOne({
          where: { id: obj.dataValues.broker_id },
        });

        obj.dataValues.broker = broker;
        obj.dataValues.site = site;

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

const getQuotationById = async (req, res) => {
  try {
    const spkg = await generateQuotations.findOne({
      where: { id: req.params.id },
    });

    if (!spkg) {
      return res.status(404).json({ msg: "Quotation not found" });
    }

    // Fetch plot details
    const plot = await Plot.findOne({
      where: { id: spkg.dataValues.plot_id },
    });

    let site = null;
    if (plot) {
      site = await Site.findOne({
        where: { id: plot.dataValues.site_id },
      });
    }

    const broker = await Broker.findOne({
      where: { id: spkg.dataValues.broker_id },
    });

    // Attach fetched details
    spkg.dataValues.broker = broker;
    spkg.dataValues.plot = plot;
    spkg.dataValues.site = site;

    res
      .status(200)
      .json({ msg: "Quotation Fetch Successfully", quotation: spkg });
  } catch (error) {
    console.error("Error fetching quotation data:", error);
    res.status(500).json({ msg: "Server error" });
  }
};

module.exports = {
  generateQuotation,
  getQuotation,
  getQuotationById,
};
