import ShippingAddress from "./ShippingAddressModel.js";
export const AddshippingAddress = async (req, res) => {
  // console.log("request came here");
  try {
    const { Name, phoneNumber, street, city, state, postalCode, country } =
      req.body;

    // console.log(req.body);
    switch (true) {
      //validation
      case !Name: {
        return res.status(404).json({ msg: "please provide Name" });
      }
      case !phoneNumber: {
        return res.status(404).json({ msg: "please provide phoneNumber" });
      }
      case !street: {
        return res.status(404).json({ msg: "please provide street" });
      }
      case !city: {
        return res.status(404).json({ msg: "please provide city" });
      }
      case !state: {
        return res.status(404).json({ msg: "please provide state" });
      }
      case !postalCode: {
        return res.status(404).json({ msg: "please provide postalCode" });
      }
      case !country: {
        return res.status(404).json({ msg: "please provide country" });
      }
    }
    req.body.user = req.user._id;
    const address = await ShippingAddress.create(req.body);

    res.status(201).json({
      success: true,
      address,
      message: "shipping Address Added",
    });
  } catch (error) {
    console.log(error.message);
    res.status(500).json({
      success: false,
      message: error.message ? error.message : "Something went Wrong",
    });
  }
};
export const AddshippingAddressByAdmin = async (req, res) => {
  try {
    const {
      Name,
      phoneNumber,
      street,
      city,
      state,
      postalCode,
      country,
      panNumber,
      tradeName,
      gstNumber,
    } = req.body;
    // console.log(req.body);
    // Validate required fields
    if (!street || !city || !state || !postalCode || !panNumber) {
      return res
        .status(400)
        .json({ msg: "Please provide all required fields" });
    }

    // Create shipping address object
    const newAddress = await ShippingAddress.create({
      Name,
      phoneNumber,
      street,
      city,
      state,
      postalCode,
      country,
      panNumber,
      tradeName,
      gstNumber,
      user: req.params._id, // Assuming req.params._id contains the correct user ID
    });

    res.status(201).json({
      success: true,
      address: newAddress,
      message: "Shipping address added successfully",
    });
  } catch (error) {
    // console.error("Error creating shipping address:", error.message);

    // Check for validation errors
    if (error.name === "ValidationError") {
      const errorMessages = Object.values(error.errors).map(
        (err) => err.message
      );
      return res.status(400).json({
        success: false,
        message: errorMessages.join(", "),
      });
    }

    // General error
    res.status(500).json({
      success: false,
      message: error.message || "Something went wrong",
    });
  }
};

// For website
export const getSingleUserSippingAddress = async (req, res) => {
  try {
    const UserShippingAddress = await ShippingAddress.find({
      user: req.user._id,
    }).sort({ createdAt: -1 });
    if (UserShippingAddress) {
      res.status(201).json({
        success: true,
        UserShippingAddress,
        message: "All User Shipping Address Fetched",
      });
    }
  } catch (error) {
    res.status(500).json({
      success: false,
      message: error.message ? error.message : "Something went Wrong",
    });
  }
};
// For Admin
export const getSingleUserSippingAddressForAdmin = async (req, res) => {
  try {
    // console.log(req.params._id);
    const UserShippingAddress = await ShippingAddress.find({
      user: req.params._id,
    }).sort({ createdAt: -1 });
    // console.log(UserShippingAddress);
    if (UserShippingAddress) {
      res.status(201).json({
        success: true,
        UserShippingAddress,
        message: "All User Shipping Address Fetched",
      });
    }
  } catch (error) {
    res.status(500).json({
      success: false,
      message: error.message ? error.message : "Something went Wrong",
    });
  }
};

///
export const deleteSelfShippingAddress = async (req, res) => {
  try {
    if (!req.params.id)
      return res
        .status(400)
        .json({ message: "please Provide shipping Address Id" });
    const getselfAddress = await ShippingAddress.findById(req.params.id);
    const userId = req.body.userId ? req.body.userId : req.user._id;
    if (!getselfAddress) {
      return res.status(404).json({
        success: false,
        message: "No shipping Address  Found!",
      });
    }
    if (getselfAddress?.user.toString() === userId.toString()) {
      const address = await ShippingAddress.findByIdAndDelete(req.params.id);
      await address.remove();
      return res.status(200).json({
        success: true,
        message: "Shipping Address Deleted Successfully!",
      });
    } else {
      return res.status(400).json({
        success: false,
        message: "you can only delete self shipping address!!",
      });
    }
  } catch (error) {
    res.status(500).json({
      success: false,
      message: error.message ? error.message : "Something went Wrong",
    });
  }
};

// update shipping addresss
export const updateShippingAddress = async (req, res) => {
  try {
    const {
      Name,
      phoneNumber,
      street,
      city,
      state,
      postalCode,
      country,
      panNumber,
      tradeName,
      gstNumber,
    } = req.body;
    // console.log(req.body);
    const _id = req.params.id;
    if (!req.params.id)
      return res
        .status(400)
        .json({ message: "please Provide shipping Address Id" });
    const getselfAddress = await ShippingAddress.findById(req.params.id);
    if (!getselfAddress) {
      return res.status(404).json({
        success: false,
        message: "No shipping Address  Found!",
      });
    }
    switch (true) {
      //validation
      case !Name: {
        return res.status(404).json({ msg: "please provide Name" });
      }
      case !phoneNumber: {
        return res.status(404).json({ msg: "please provide phone_Number" });
      }
      case !street: {
        return res.status(404).json({ msg: "please provide street" });
      }
      case !city: {
        return res.status(404).json({ msg: "please provide city" });
      }
      case !state: {
        return res.status(404).json({ msg: "please provide state" });
      }
      case !postalCode: {
        return res.status(404).json({ msg: "please provide postalCode" });
      }
      case !country: {
        return res.status(404).json({ msg: "please provide country" });
      }
      case !panNumber: {
        return res.status(404).json({ msg: "please provide panNumber" });
      }
      case !tradeName: {
        return res.status(404).json({ msg: "please provide tradeName" });
      }
      case !gstNumber: {
        return res.status(404).json({ msg: "please provide gstNumber" });
      }
    }
    const updateAddressData = {
      Name,
      phoneNumber,
      street,
      city,
      state,
      postalCode,
      country,
      panNumber,
      tradeName,
      gstNumber,
    };
    const updateShippingAddress = await ShippingAddress.findByIdAndUpdate(
      { _id: _id },
      { $set: updateAddressData },
      { new: true }
    );

    res.status(201).json({
      success: true,
      updateShippingAddress,
      message: "Shipping Address updated",
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: error.message ? error.message : "Something went Wrong",
    });
  }
};

export const getSingleSippingAddress = async (req, res) => {
  try {
    let _id = req.params.id;
    const address = await ShippingAddress.findById({ _id: _id });

    if (address) {
      res.status(201).json({
        success: true,
        address,
        message: "Shipping Address Fetched",
      });
    }
  } catch (error) {
    res.status(500).json({
      success: false,
      message: error.message ? error.message : "Something went Wrong",
    });
  }
};
