import mongoose from "mongoose";
import { BrandModel } from "./BrandsModel.js";

// Add new Brand
export const addBrand = async (req, res) => {
  const { brandName } = req.body;

  if (!req?.user) {
    return res.status(400).json({ message: "Please login!" });
  }

  try {
    if (!mongoose.Types.ObjectId.isValid(req.user._id)) {
      return res.status(400).json({ message: "Please login again." });
    }

    if (!brandName) {
      return res.status(400).json({ message: "Please provide a brand name" });
    }

    const brand = await BrandModel.create({
      brandName,
      addedBy: req.user._id,
    });

    return res.status(201).json({ success: true, brand, message: "Brand added successfully" });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: error.message || "Something went wrong",
    });
  }
};

// Get all Brands
export const getBrands = async (req, res) => {
  try {
    const PAGE_SIZE = parseInt(req.query.show) || 10;
    const page = parseInt(req.query.page) || 1;
    const skip = (page - 1) * PAGE_SIZE;
    let filter = {};

    // Search by brandName if provided
    if (req.query.brandName) {
      filter.brandName = {
        $regex: new RegExp(req.query.brandName, "i"), // Case-insensitive search
      };
    }

    // Get total number of brands matching the filter
    const total = await BrandModel.countDocuments(filter);

    // Fetch brands with pagination and filtering
    const brands = await BrandModel.find(filter)
      .limit(PAGE_SIZE)
      .skip(skip)
      .sort({ createdAt: -1 })
      .exec();

    // If no brands are found, return 404 error
    if (!brands.length) {
      return res.status(404).json({ message: "No brands found" });
    }

    // Return the paginated and filtered brands list
    res.status(200).json({
      success: true,
      total_data: total,
      total_pages: Math.ceil(total / PAGE_SIZE),
      current_page: page,
      brands,
    });
  } catch (error) {
    // Handle server error
    res.status(500).json({
      success: false,
      message: error.message || "Something went wrong",
    });
  }
};

// Update Brand
export const updateBrand = async (req, res) => {
  const { _id } = req.params;
  const { brandName } = req.body;

  if (!req?.user) {
    return res.status(400).json({ message: "Please login!" });
  }

  if (!mongoose.Types.ObjectId.isValid(_id)) {
    return res.status(404).json({ message: "Invalid brand ID" });
  }

  try {
    const updatedBrand = await BrandModel.findByIdAndUpdate(
      _id,
      { brandName },
      { new: true, runValidators: true }
    );

    if (!updatedBrand) {
      return res.status(404).json({ message: "Brand not found" });
    }

    res.status(200).json({ success: true, updatedBrand, message: "Brand updated successfully" });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: error.message || "Something went wrong",
    });
  }
};

// Delete Brand
export const deleteBrand = async (req, res) => {
  const { _id } = req.params;

  if (!req?.user) {
    return res.status(400).json({ message: "Please login!" });
  }

  if (!mongoose.Types.ObjectId.isValid(_id)) {
    return res.status(404).json({ message: "Invalid brand ID" });
  }

  try {
    const deletedBrand = await BrandModel.findByIdAndDelete(_id);

    if (!deletedBrand) {
      return res.status(404).json({ message: "Brand not found" });
    }

    res.status(200).json({ success: true, deletedBrand, message: "Brand deleted successfully" });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: error.message || "Something went wrong",
    });
  }
};
