const Car = require('../models/cars');
const Collection = require('../models/collection');
const path = require("path");
const user = require('../models/user');

exports.createCar = async (req, res) => {
  try {
    // 1) Multer must have put the file under req.file
    if (!req.file) {
      return res.status(400).json({ message: "Image file is required." });
    }

    // 2) Validate text fields
    const { make, model, year, modifications } = req.body;
    if (!make || !model || !year || !modifications) {
      return res
        .status(400)
        .json({ message: "make, model, year, and modifications are required." });
    }

    // 3) Build image path (leading slash because /uploads is served statically)
    const imagePath = `/uploads/cars/${req.file.filename}`;

    // 4) Create the Car document
    const newCar = await Car.create({
      image: imagePath,
      make: make.trim(),
      model: model.trim(),
      year: Number(year),
      modifications: modifications.trim(),
    });

    // 5) Find the logged-in user's ID
    const userId = req.user.userId || req.user.id || req.user._id;
    if (!userId) {
      return res
        .status(400)
        .json({ message: "User ID not found in token payload." });
    }

    // 6) Find or create that user’s Collection
    let userCollection = await Collection.findOne({ user_id: userId });
    if (!userCollection) {
      userCollection = await Collection.create({
        user_id: userId,
        cars: [newCar._id],
      });
    } else {
      userCollection.cars.push(newCar._id);
      await userCollection.save();
    }

    let founduser = await user.findById(userId);
    if (!founduser) {
      return res.status(404).json({ message: "User not found" });
    }

    // update number of cars in the collection
    founduser.number_of_cars = userCollection.cars.length;
    await founduser.save();

    // 7) Return success
    return res.status(201).json({
      message: "Car added successfully",
      car: newCar,
    });
  } catch (error) {
    console.error("Error creating car:", error);
    return res.status(500).json({
      message: "Server error while adding car",
      error: error.message,
    });
  }
};

exports.getCollection = async (req, res) => {
  try {
    // 1) Get userId from req.user
    const userId = req.user.userId || req.user.id || req.user._id;
    if (!userId) {
      return res
        .status(400)
        .json({ message: "User ID not found in token payload." });
    }

    // 2) Find the user's collection, populate car details
    const collection = await Collection.findOne({ user_id: userId })
      .populate("cars")
      .exec();

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

    const host = req.get("host");
    const protocol = req.protocol;

    const carsWithFullUrl = collection.cars.map((car) => {
      // car.image is something like "/uploads/cars/<filename>"
      const fullImageUrl = `${protocol}://${host}${car.image}`;

      return {
        _id: car._id,
        make: car.make,
        model: car.model,
        year: car.year,
        modifications: car.modifications,
        // return the fully qualified URL instead of the raw path
        image: fullImageUrl,
        createdAt: car.createdAt,
        updatedAt: car.updatedAt,
      };
    });

    return res.status(200).json({
      _id: collection._id,
      user_id: collection.user_id,
      cars: carsWithFullUrl,
    });
  } catch (error) {
    console.error("Error retrieving collection:", error);
    return res.status(500).json({
      message: "Server error while retrieving collection",
      error: error.message,
    });
  }
};