import Car from "../models/Car.js";

// Get all cars
export const getAllCars = async (req, res) => {
  try {
    const { search, status, page = 1, limit = 10 } = req.query;

    let query = {};

    // Search by brand, model, or plate number
    if (search) {
      query.$or = [
        { brand: { $regex: search, $options: "i" } },
        { model: { $regex: search, $options: "i" } },
        { plateNumber: { $regex: search, $options: "i" } }
      ];
    }

    // Filter by status
    if (status) {
      query.status = status;
    }

    const skip = (parseInt(page) - 1) * parseInt(limit);

    const cars = await Car.find(query)
      .skip(skip)
      .limit(parseInt(limit))
      .sort({ createdAt: -1 });

    const total = await Car.countDocuments(query);

    res.json({
      cars,
      total,
      page: parseInt(page),
      pages: Math.ceil(total / parseInt(limit))
    });
  } catch (error) {
    console.error("Get all cars error:", error);
    res.status(500).json({ message: "Server error" });
  }
};

// Get single car
export const getCar = async (req, res) => {
  try {
    const car = await Car.findById(req.params.id);
    if (!car) {
      return res.status(404).json({ message: "Car not found" });
    }
    res.json(car);
  } catch (error) {
    console.error("Get car error:", error);
    res.status(500).json({ message: "Server error" });
  }
};

// Create car (admin only)
export const createCar = async (req, res) => {
  try {
    const { plateNumber, brand, model, year, color, dailyRate, image, status } = req.body;

    // Check if plate number exists
    const existingCar = await Car.findOne({ plateNumber });
    if (existingCar) {
      return res.status(400).json({ message: "Car with this plate number already exists" });
    }

    const car = new Car({
      plateNumber,
      brand,
      model,
      year,
      color,
      dailyRate,
      image: image || "",
      status: status || "available"
    });

    await car.save();

    res.status(201).json({ message: "Car created successfully", car });
  } catch (error) {
    console.error("Create car error:", error);
    res.status(500).json({ message: "Server error" });
  }
};

// Update car
export const updateCar = async (req, res) => {
  try {
    const { plateNumber, brand, model, year, color, dailyRate, image, status } = req.body;

    const car = await Car.findByIdAndUpdate(
      req.params.id,
      { plateNumber, brand, model, year, color, dailyRate, image, status },
      { new: true }
    );

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

    res.json({ message: "Car updated successfully", car });
  } catch (error) {
    console.error("Update car error:", error);
    res.status(500).json({ message: "Server error" });
  }
};

// Delete car
export const deleteCar = async (req, res) => {
  try {
    const car = await Car.findByIdAndDelete(req.params.id);
    if (!car) {
      return res.status(404).json({ message: "Car not found" });
    }
    res.json({ message: "Car deleted successfully" });
  } catch (error) {
    console.error("Delete car error:", error);
    res.status(500).json({ message: "Server error" });
  }
};