const Service = require("../../models/admin/serviceModal");
const { errorResponse } = require("../../utils/errorResponseHandler");
const { logUserAction } = require("../../utils/userActionLogger");

// Create Service
const createService = async (req, res) => {
  try {
    const { serviceName, serviceCost, orgId } = req.body;

    if (!serviceName ) return errorResponse(res, "Service name is required", 400);
    if (!serviceCost) return errorResponse(res, "Service cost is required", 400);
    if (!orgId) return errorResponse(res, "Organization ID is required", 400);

    const userId = req.user?._id;

    // Check if service with same name exists in the org
    const existingService = await Service.findOne({ serviceName, orgId });
    if (existingService) {
      return errorResponse(res, "Service name already exists in this organization", 409);
    }

    const service = await Service.create({
      serviceName,
      serviceCost,
      orgId,
      createdBy: userId || null,
      updatedBy: null,
    });

    // Log user action
    await logUserAction({
      userId,
      orgId,
      action: "CREATE",
      model: "Service",
      details: { serviceId: service._id, serviceName },
      req,
    });

    res.status(201).json({ success: true, data: service });
  } catch (error) {
    return errorResponse(res, "Failed to create service", 400, error);
  }
};

// Get All Services with Pagination (exclude soft deleted)
const getServices = async (req, res) => {
  try {
    let { page = 1, limit = 10 } = req.query;
    page = parseInt(page);
    limit = parseInt(limit);
    const skip = (page - 1) * limit;

    const query = { isDeleted: false };

    const [services, total] = await Promise.all([
      Service.find(query)
        .populate("createdBy", "firstName lastName email")
        .populate("updatedBy", "firstName lastName email")
        .populate("orgId", "orgName")
        .skip(skip)
        .limit(limit)
        .sort({ createdAt: -1 }),
      Service.countDocuments(query),
    ]);

    // Log user action
    await logUserAction({
      // userId: req.user?._id,
      userId: req.user?.id,
      orgId: req.user?.orgId || null,
      action: "READ",
      model: "Service",
      details: { page, limit, count: services.length },
      req,
    });

    res.status(200).json({
      success: true,
      page,
      totalPages: Math.ceil(total / limit),
      totalRecords: total,
      data: services,
    });
  } catch (error) {
    return errorResponse(res, "Failed to fetch services", 500, error);
  }
};

// Get Service by ID
const getServiceById = async (req, res) => {
  try {
    const service = await Service.findById(req.params.id)
      .populate("createdBy", "firstName lastName email")
      .populate("updatedBy", "firstName lastName email")
      .populate("orgId", "orgName");

    if (!service) return errorResponse(res, "Service not found", 404);

    // Log user action
    await logUserAction({
      // userId: req.user?._id,
      userId: req.user?.id,
      orgId: service.orgId?._id || null,
      action: "READ",
      model: "Service",
      details: { serviceId: service._id },
      req,
    });

    res.status(200).json({ success: true, data: service });
  } catch (error) {
    return errorResponse(res, "Error fetching service", 500, error);
  }
};

// Update Service
// const updateService = async (req, res) => {
//   try {
//     const { status, serviceName } = req.body;
//     const userId = req.user?._id;

//     const updateData = { updatedBy: userId || null, updatedAt : new Date(), };
//     if (status !== undefined) updateData.status = status;
//     if (serviceName) updateData.serviceName = serviceName;

//     const service = await Service.findByIdAndUpdate(
//       req.params.id,
//       updateData,
//       { new: true, runValidators: true }
//     )
//       .populate("createdBy", "firstName lastName email")
//       .populate("updatedBy", "firstName lastName email")
//       .populate("orgId", "orgName");

//     if (!service) return errorResponse(res, "Service not found", 404);

//     // Log user action
//     await logUserAction({
//       userId,
//       orgId: service.orgId?._id || null,
//       action: "UPDATE",
//       model: "Service",
//       details: { serviceId: service._id, updatedFields: updateData },
//       req,
//     });

//     res.status(200).json({ success: true, data: service });
//   } catch (error) {
//     return errorResponse(res, "Failed to update service", 400, error);
//   }
// };
const updateService = async (req, res) => {
  try {
    const { status, serviceName, serviceCost  } = req.body;
    const userId = req.user?._id;

    // 🔥 DUPLICATE CHECK (exclude current service)
    if (serviceName) {
      const duplicate = await Service.findOne({
        _id: { $ne: req.params.id },
        serviceName: { $regex: `^${serviceName}$`, $options: "i" },
        orgId: req.user.orgId,
        isDeleted: false,
      });

      if (duplicate) {
        return errorResponse(
          res,
          "Service already exists in this organization",
          409
        );
      }
    }

    const updateData = {
      updatedBy: userId || null,
      updatedAt: new Date(),
    };

    if (status !== undefined) updateData.status = status;
    if (serviceCost !== undefined) updateData.serviceCost = serviceCost;
    if (serviceName) updateData.serviceName = serviceName;

    const service = await Service.findByIdAndUpdate(
      req.params.id,
      updateData,
      { new: true, runValidators: true }
    )
      .populate("createdBy", "firstName lastName email")
      .populate("updatedBy", "firstName lastName email")
      .populate("orgId", "orgName");

    if (!service) return errorResponse(res, "Service not found", 404);

    await logUserAction({
      userId,
      orgId: service.orgId?._id || null,
      action: "UPDATE",
      model: "Service",
      details: { serviceId: service._id, updatedFields: updateData },
      req,
    });

    return res.status(200).json({ success: true, data: service });
  } catch (error) {
    return errorResponse(res, "Failed to update service", 400, error);
  }
};


// Soft Delete Service
const deleteService = async (req, res) => {
  try {
    const userId = req.user?._id;

    const service = await Service.findByIdAndUpdate(
      req.params.id,
      { isDeleted: true, updatedBy: userId || null },
      { new: true }
    );

    if (!service) return errorResponse(res, "Service not found", 404);

    // Log user action
    await logUserAction({
      userId,
      orgId: service.orgId?._id || null,
      action: "DELETE",
      model: "Service",
      details: { serviceId: service._id },
      req,
    });

    res.status(200).json({
      success: true,
      message: "Service deleted successfully",
      data: service,
    });
  } catch (error) {
    return errorResponse(res, "Failed to delete service", 500, error);
  }
};

module.exports = {
  createService,
  getServices,
  getServiceById,
  updateService,
  deleteService,
};
