import { AffiliateModel } from "./AffiliateModel.js";

// -----------------------------AFFILIATE & COUPONS ARE HARDLY BINDED DATA--------------------------------------------------------
//Create Affiliate
export const createAffiliate = async (req, res) => {
  try {
    const result = req.body;
    const affiliate = new AffiliateModel(result);
    const savedData = await affiliate.save();
    if (savedData) {
      return res
        .status(201)
        .json({ success: true, message: "Affiliate Added" });
    }
  } catch (error) {
    res.status(500).json({
      success: false,
      message: error.message
        .split(":")
        .splice(1)
        .join(":")
        .trim()
        .split(":")
        .splice(1)
        .join(":")
        .trim(),
    });
  }
};

//EDIT
export const editAffiliate = async (req, res) => {
  const updateFields = {};

  const {
    name,
    mobile,
    email,
    country,
    state,
    city,
    address,
    pincode,
    nameAsBank,
    accountNo,
    ifsc,
    bankName,
    branchName,
  } = req.body;

  // Add only the fields that are present in the request body to the updateFields object
  if (name) updateFields.name = name;
  if (mobile) updateFields.mobile = mobile;
  if (email) updateFields.email = email;
  if (country) updateFields.country = country;
  if (state) {
    updateFields.state = state;
  } else {
    updateFields.state = "";
  }
  if (city) {
    updateFields.city = city;
  } else {
    updateFields.city = "";
  }
  if (address) updateFields.address = address;
  if (pincode) updateFields.pincode = pincode;
  if (nameAsBank) updateFields.nameAsBank = nameAsBank;
  if (accountNo) updateFields.accountNo = accountNo;
  if (ifsc) updateFields.ifsc = ifsc;
  if (bankName) updateFields.bankName = bankName;
  if (branchName) updateFields.branchName = branchName;
  try {
    const saveData = await AffiliateModel.findByIdAndUpdate(
      { _id: req.params.id },
      { $set: updateFields },
      { new: true }
    );
    res.json({
      success: true,
      message: "Affiliate Updated Succesfully",
    });
  } catch (error) {
    res.status(400).json({
      success: false,
      message: "Error in Updation",
    });
  }
};
//DELETE
export const deleteAffiliate = async (req, res) => {};
//PAY AFFILIATE TODO
export const payAffiliate = async (req, res) => {
  // console.log(req.body);
  const { noOfCoupons, amountToPay, amount, transecId, date, time } = req.body;
  if (
    !req.params.id ||
    !noOfCoupons ||
    !amountToPay ||
    !amount ||
    !transecId ||
    !date ||
    !time
  ) {
    return res.status(400).json({
      success: false,
      message: "Error in Payment",
    });
  }
  try {
    const affiliate = await AffiliateModel.findById(req.params.id);
    //Checking if it's valid data from the client
    if (
      amountToPay != affiliate.total_earning - affiliate.paid_amount ||
      noOfCoupons != affiliate.coupon_claimed - affiliate.no_of_paid_coupon
    ) {
      return res.status(400).json({
        success: false,
        message: "Data invalid",
      });
    }

    // Construct the update operation
    const updateOperation = {
      $push: {
        affiliate_pay_history: {
          amount: amountToPay,
          transecId: transecId,
          date: date,
          time: time,
        },
      },
      $inc: {
        paid_amount: amountToPay,
        no_of_paid_coupon: noOfCoupons,
      },
    };

    // Execute the update operation
    const updatedAffiliate = await AffiliateModel.findByIdAndUpdate(
      req.params.id,
      updateOperation,
      { new: true }
    );

    return res.json({
      success: true,
      message: "Payment Done Successfully",
      updatedAffiliate: { updatedAffiliate },
    });
  } catch (error) {
    console.error(error);
    return res.status(400).json({
      success: false,
      message: "Error in Payment",
    });
  }
};

//GET ONE AFFLILIATE
export const getOneAffiliate = async (req, res) => {
  if (req.params?.id) {
    try {
      const saveData = await AffiliateModel.findById(req.params.id);
      const resObj = {
        name: saveData.name,
        mobile: saveData.mobile,
        email: saveData.email,
        country: saveData.country,
        state: saveData.state,
        city: saveData.city,
        address: saveData.address,
        pincode: saveData.pincode,
        nameAsBank: saveData.nameAsBank,
        accountNo: saveData.accountNo,
        ifsc: saveData.ifsc,
        bankName: saveData.bankName,
        branchName: saveData.branchName,
      };
      res.status(200).json({
        success: true,
        message: resObj,
      });
    } catch (error) {
      res.status(400).json({
        success: false,
        message: "Error in getting Affiliates",
      });
    }
  }
};
//LIST ALL AFFILIATE
export const listAllAffiliate = async (req, res) => {
  try {
    const affiliate = await AffiliateModel.find(
      {},
      {
        name: 1,
        _id: 1,
        coupon_claimed: 1,
        coupon_code: 1,
        total_earning: 1,
        paid_amount: 1,
        is_affiliate_active: 1,
      }
    ).sort({ createdAt: -1 });
    res.status(200).json({
      success: true,
      message: affiliate,
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      messgae: error.message ? error.message : "Something went wrong!",
    });
  }
};

//Activate & Deactivate Affiliates
export const suspendAffiliate = async (req, res) => {
  const { id, is_affiliate_active } = req.body;
  try {
    const saveData = await AffiliateModel.findByIdAndUpdate(id, {
      is_affiliate_active: is_affiliate_active,
    });
    res.status(200).json({
      success: true,
      message: "Success",
    });
  } catch (error) {
    res.status(400).json({
      success: false,
      message: "Affiliate Doesn't Exists",
    });
  }
};

//Get Affiliate data for payment
export const getOneAffiliateForPay = async (req, res) => {
  if (req.params?.id) {
    try {
      const saveData = await AffiliateModel.findById(req.params.id);
      const resObj = {
        name: saveData.name,
        coupon_claimed: saveData.coupon_claimed,
        total_earning: saveData.total_earning,
        paid_amount: saveData.paid_amount,
        no_of_paid_coupon: saveData.no_of_paid_coupon,
        affiliate_discount_amount: saveData.affiliate_discount_amount,
        coupon_code: saveData.coupon_code,
        nameAsBank: saveData.nameAsBank,
        accountNo: saveData.accountNo,
        ifsc: saveData.ifsc,
        bankName: saveData.bankName,
        branchName: saveData.branchName,
      };
      res.status(200).json({
        success: true,
        message: resObj,
      });
    } catch (error) {
      res.status(400).json({
        success: false,
        message: "Error in getting Affiliates",
      });
    }
  }
};
//Get Affiliate data for History
export const affiliatePayHistory = async (req, res) => {
  if (req.params?.id) {
    try {
      const saveData = await AffiliateModel.findById(req.params.id).sort({
        updatedAt: -1,
      });
      const resObj = {
        affiliate_pay_history: saveData.affiliate_pay_history,
        name: saveData.name,
      };
      res.status(200).json({
        success: true,
        message: resObj,
      });
    } catch (error) {
      res.status(400).json({
        success: false,
        message: "Error in getting History",
      });
    }
  }
};
