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

// Get dashboard statistics
export const getDashboardStats = async (req, res) => {
  try {
    // Count users (clients only)
    const totalClients = await User.countDocuments({ role: "client" });

    // Count cars
    const totalCars = await Car.countDocuments();

    // Count available cars
    const availableCars = await Car.countDocuments({ status: "available" });

    // Count rented cars
    const rentedCars = await Car.countDocuments({ status: "rented" });

    // Count active rentals
    const activeRentals = await Rental.countDocuments({ status: "active" });

    // Count returned rentals
    const returnedRentals = await Rental.countDocuments({ status: "returned" });

    // Calculate total revenue
    const rentals = await Rental.find({ status: "returned" });
    const totalRevenue = rentals.reduce((sum, rental) => sum + (rental.totalAmount || 0), 0);

    // Get recent rentals
    const recentRentals = await Rental.find()
      .populate("client", "fullName")
      .populate("car", "plateNumber brand model")
      .sort({ createdAt: -1 })
      .limit(5);

    // Get recent clients
    const recentClients = await User.find({ role: "client" })
      .select("fullName email createdAt")
      .sort({ createdAt: -1 })
      .limit(5);

    // Most rented cars
    const rentalStats = await Rental.aggregate([
      { $group: { _id: "$car", count: { $sum: 1 } } },
      { $sort: { count: -1 } },
      { $limit: 5 }
    ]);

    const mostRentedCarIds = rentalStats.map(stat => stat._id);
    const mostRentedCars = await Car.find({ _id: { $in: mostRentedCarIds } });

    // Cars by status
    const carsByStatus = await Car.aggregate([
      { $group: { _id: "$status", count: { $sum: 1 } } }
    ]);

    const statusSummary = {
      available: 0,
      rented: 0,
      maintenance: 0
    };

    carsByStatus.forEach(item => {
      statusSummary[item._id] = item.count;
    });

    res.json({
      totalClients,
      totalCars,
      availableCars,
      rentedCars,
      activeRentals,
      returnedRentals,
      totalRevenue,
      recentRentals,
      recentClients,
      mostRentedCars,
      statusSummary
    });
  } catch (error) {
    console.error("Get dashboard stats error:", error);
    res.status(500).json({ message: "Server error" });
  }
};

// Get client dashboard stats
export const getClientDashboardStats = async (req, res) => {
  try {
    const userId = req.userId;

    // Available cars count
    const availableCarsCount = await Car.countDocuments({ status: "available" });

    // Active rentals count for this client
    const activeRentalsCount = await Rental.countDocuments({
      client: userId,
      status: "active"
    });

    // Total rentals count for this client
    const totalRentalsCount = await Rental.countDocuments({ client: userId });

    // Recent rentals for this client
    const myRecentRentals = await Rental.find({ client: userId })
      .populate("car", "plateNumber brand model dailyRate")
      .sort({ createdAt: -1 })
      .limit(5);

    res.json({
      availableCarsCount,
      activeRentalsCount,
      totalRentalsCount,
      myRecentRentals
    });
  } catch (error) {
    console.error("Get client dashboard stats error:", error);
    res.status(500).json({ message: "Server error" });
  }
};