import Booking from "../DB/Model/booking.modal.js";
import Rating from "../DB/Model/rating.modal.js";
import Service from "../DB/Model/service.modal.js";
import serviceRequest from "../DB/Model/serviceRequest.js";
import serviceCategory from "../DB/Model/services_category.modal.js";
import User from "../DB/Model/user.model.js";

export const createService = async (req, res) => {
    try {
        const created_by = req.user._id;
        const service = await Service.create({
            ...req.body,
            created_by,
        });

        res.status(201).json({
            status: true,
            message: "Service created successfully.",
            data: service,
        });
    } catch (err) {
        res.status(500).json({ status: false, message: err.message });
    }
};
export const getServices = async (req, res) => {
  try {
    const { category, pricing_type, availability, isRequested } = req.query;

    const filter = {
      isApproved: false,
      isDeleted: false,
    };

    if (category) filter.category = category;
    if (pricing_type) filter.pricing_type = pricing_type;
    if (availability) filter.availability = availability;
    if (isRequested === "true") filter.isRequested = true;

    // Fetch services
    const services = await Service.find(filter)
      .populate({
        path: "created_by",
        select:
          "full_name averageRating phone_number state city country image",
        populate: {
          path: "image",
          select: "file",
        },
      })
      .populate("service_category")
      .populate("image");

    // Fetch bookings & ratings for each service
    const serviceWithRatings = await Promise.all(
      services.map(async (service) => {
        // Get all bookings related to this service
        const bookings = await Booking.find({ serviceId: service._id });

        // Get all ratings for those bookings
        const bookingIds = bookings.map((b) => b._id);
        const ratings = await Rating.find({ bookingId: { $in: bookingIds } })
          .populate({
            path: "userId",
            select: "full_name email image",
            populate: {
              path: "image",
              select: "file",
            },
          })
          .populate({
            path: "receiverId",
            select: "full_name email image",
            populate: {
              path: "image",
              select: "file",
            },
          });

        // Attach ratings to the service
        return {
          ...service.toObject(),
          ratings,
        };
      })
    );

    res.status(200).json({
      status: true,
      message: "Services fetched successfully with ratings.",
      data: serviceWithRatings,
    });
  } catch (err) {
    res.status(500).json({ status: false, message: err.message });
  }
};
export const getServiceById = async (req, res) => {
    try {
        const service = await Service.findById(req.params.id).populate("created_by", "full_name")
            .populate("image");
        if (!service) {
            return res
                .status(404)
                .json({ status: false, message: "Service not found." });
        }
        res.status(200).json({ status: true, data: service });
    } catch (err) {
        res.status(500).json({ status: false, message: err.message });
    }
};
export const updateService = async (req, res) => {
    try {
        const service = await Service.findById(req.params.id);
        console.log('service:', service);
        if (!service) {
            return res
                .status(404)
                .json({ status: false, message: "Service not found." });
        }

        // Check if the logged-in user is the creator
        if (service.created_by.toString() !== req.user._id.toString()) {
            return res
                .status(403)
                .json({ status: false, message: "Unauthorized to update this service." });
        }

        // Proceed with update
        const updatedService = await Service.findByIdAndUpdate(req.params.id, req.body, {
            new: true,
        });

        res.status(200).json({
            status: true,
            message: "Service updated successfully.",
            data: updatedService,
        });
    } catch (err) {
        res.status(500).json({ status: false, message: err.message });
    }
};
export const deleteService = async (req, res) => {
    try {
        const service = await Service.findById(req.params.id);

        if (!service) {
            return res
                .status(404)
                .json({ status: false, message: "Service not found." });
        }

        // Check if the logged-in user is the creator
        if (service.created_by.toString() !== req.user._id.toString()) {
            return res
                .status(403)
                .json({ status: false, message: "Unauthorized to delete this service." });
        }

        service.isDeleted = true;
        await service.save();

        res.status(200).json({
            status: true,
            message: "Service deleted successfully.",
        });
    } catch (err) {
        res.status(500).json({ status: false, message: err.message });
    }
};
export const updateServiceStatus = async (req, res) => {
    try {
        const userId = req.user._id;
        const userType = req.user.userType;
        const serviceId = req.params.id;
        const { status } = req.body;

        const allowedStatus = ["in_progress", "completed"];
        if (!allowedStatus.includes(status)) {
            return res.status(400).json({ status: false, message: "Invalid status" });
        }

        const service = await Service.findById(serviceId);
        if (!service) {
            return res.status(404).json({ status: false, message: "Service not found" });
        }

        if (status === "in_progress") {
            // Only normal user can set to in_progress
            if (userType !== "user") {
                return res.status(403).json({ status: false, message: "Only normal users can set to in_progress" });
            }
            if (!service.accepted_by) {
                service.accepted_by = userId;
            }
        }

        if (status === "completed") {
            // Only service provider can set to completed
            if (userType !== "service_provider") {
                return res.status(403).json({ status: false, message: "Only service providers can set to completed" });
            }
        }

        service.status = status;
        await service.save();

        return res.status(200).json({
            status: true,
            message: `Status updated to ${status}`,
            data: service
        });

    } catch (error) {
        console.error("Status update error:", error);
        return res.status(500).json({ status: false, message: "Internal server error" });
    }
};
export const getServiceProviderBookingStats = async (req, res) => {
    try {
        const userId = req.user._id;

        const [pendingCount, completedCount] = await Promise.all([
            Booking.countDocuments({ accepted_by: userId, status: "pending" }),
            Booking.countDocuments({ accepted_by: userId, status: "completed" }),
        ]);

        return res.status(200).json({
            status: true,
            message: "Service provider booking stats",
            data: {
                total_pending: pendingCount,
                total_completed: completedCount,
            },
        });
    } catch (error) {
        console.error("Booking stats error:", error);
        return res.status(500).json({
            status: false,
            message: "Internal server error",
        });

    }
};
export const getAllServiceCategory = async (req, res) => {
    try {

        const data = await serviceCategory.find();
        if (!data) {
            return res.status(404).json({
                status: false,
                message: "No categories found"
            });
        }
        return res.status(200).json({
            status: true,
            message: "All service categories",
            data: data
        });

    } catch (error) {
        return res.status(500).json({
            status: false,
            message: "Internal server error"
        })
    }
}
export const getAllUsers = async (req, res) => {
    try {
        const { zip_code } = req.query;

        const filter = {};
        if (zip_code) {
            filter.zip_code = zip_code;
        }

        const users = await User.find(filter, "full_name zip_code image phone_number averageRating city state country")
            .populate("image", "file");

        if (!users || users.length === 0) {
            return res.status(404).json({
                status: false,
                message: "No users found"
            });
        }

        return res.status(200).json({
            status: true,
            message: "Users retrieved successfully",
            data: users
        });

    } catch (error) {
        return res.status(500).json({
            status: false,
            message: "Internal server error",
            error: error.message
        });
    }
};
export const getSingleUser = async (req, res) => {
    try {
        const userId = req.params.id;

        // ✅ 1. Get user basic details
        const user = await User.findOne(
            { _id: userId },
            "full_name zip_code image averageRating state country city email phone_number"
        ).populate("image", "file");

        if (!user) {
            return res.status(404).json({
                status: false,
                message: "User not found",
            });
        }

        // ✅ 2. Get booking history where user was accepted as carrier
        const bookingHistory = await Booking.find({ accepted_by: userId }).populate("serviceId")

        // ✅ 3. Count total bookings
        const totalBookings = bookingHistory.length;

        // ✅ 4. Total earnings logic (currently disabled)
        /*
        const totalEarnings = bookingHistory.reduce((sum, booking) => {
          return sum + (booking?.fare || 0); // Replace 'fare' with your earnings field if needed
        }, 0);
        */

        // ✅ 5. Get all services created by user
        const allServices = await Service.find({ created_by: userId });

        // ✅ 6. Get all ratings where user is the receiver
        const ratings = await Rating.find({ receiverId: userId });

        // ✅ 7. Return response (earnings excluded)
        return res.status(200).json({
            status: true,
            message: "User retrieved successfully",
            data: {
                user,
                totalBookings,
                // totalEarnings, // <== commented out from response
                bookingHistory,
                // allServices,
                ratings,
            },
        });
    } catch (error) {
        return res.status(500).json({
            status: false,
            message: "Internal server error",
            error: error.message,
        });
    }
};
