const QCParam = require("../../models/securityops/qcParamModel");
const { errorResponse } = require("../../utils/errorResponseHandler");
const { logUserAction } = require("../../utils/userActionLogger");
const qcService = require("../../services/securityops/qcService");

const createQCParam = async (req, res) => {
  try {
    const { parameterName, value } = req.body;
    // console.log(req.user._id);

    if (!parameterName) {
      return res.status(400).json({
        success: false,
        message: "Parameter name is required",
      });
    }

    const existing = await QCParam.findOne({
      parameterName: parameterName.trim(),
      isDeleted: { $ne: true },
    });

    if (existing) {
      return res.status(400).json({
        success: false,
        message: "Parameter already exists",
      });
    }

    const param = await QCParam.create({
      parameterName: parameterName.trim(),
      value,
      createdBy: req.session.user?.id,
    });

    // await logUserAction(req.user?.id, "QC_PARAM_CREATE", `Created parameter ${parameterName}`);

    return res.status(201).json({
      success: true,
      message: "Parameter created successfully",
      data: param,
    });
  } catch (error) {
    return errorResponse(res, error);
  }
};

const getQCParams = async (req, res) => {
  try {
    const {
      page = 1,
      limit = 10,
      search = "",
      sortBy = "createdAt",
      order = "desc",
    } = req.query;

    const pageNumber = parseInt(page);
    const pageSize = parseInt(limit);
    const sortOrder = order === "asc" ? 1 : -1;

    const filter = {
      isDeleted: { $ne: true },
    };

    if (search) {
      filter.$or = [
        { parameterName: { $regex: search, $options: "i" } },
        { unit: { $regex: search, $options: "i" } },
      ];
    }

    const totalRecords = await QCParam.countDocuments(filter);

    const params = await QCParam.find({
      isDeleted: { $ne: true },
    })
      .populate("createdBy", "firstName")
      .populate("updatedBy", "firstName")
      .sort({ createdAt: -1 })
      .skip((pageNumber - 1) * pageSize)
      .limit(pageSize);

    return res.status(200).json({
      success: true,
      message: "Parameters fetched successfully",
      data: params,
      pagination: {
        totalRecords,
        currentPage: pageNumber,
        totalPages: Math.ceil(totalRecords / pageSize),
        pageSize,
      },
    });
  } catch (error) {
    return errorResponse(res, error);
  }
};

const deleteQCParam = async (req, res) => {
  try {
    const { id } = req.params;

    const param = await QCParam.findById(id);

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

    param.isDeleted = true;
    param.updatedBy = req.user?.id || null;

    await param.save();

    // await logUserAction(req.user?.id, "QC_PARAM_DELETE", `Deleted parameter ${param.parameterName}`);

    return res.status(200).json({
      success: true,
      message: "Parameter deleted successfully",
    });
  } catch (error) {
    return errorResponse(res, error);
  }
};

const updateQCParam = async (req, res) => {
  try {
    const { id } = req.params;
    const { parameterName, value } = req.body;

    if (!parameterName) {
      return res.status(400).json({
        success: false,
        message: "Parameter name is required",
      });
    }

    const param = await QCParam.findOne({
      _id: id,
      isDeleted: { $ne: true },
    });

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

    // Prevent duplicate parameter names
    const existing = await QCParam.findOne({
      _id: { $ne: id },
      parameterName: parameterName.trim(),
      isDeleted: { $ne: true },
    });

    if (existing) {
      return res.status(400).json({
        success: false,
        message: "Parameter already exists",
      });
    }

    param.parameterName = parameterName.trim();
    param.value = value || null;
    param.updatedBy = req.user?.id || null;

    await param.save();

    // await logUserAction(req.user?.id, "QC_PARAM_UPDATE", `Updated parameter ${parameterName}`);

    return res.status(200).json({
      success: true,
      message: "Parameter updated successfully",
      data: param,
    });
  } catch (error) {
    return errorResponse(res, error);
  }
};

const updateQCParameter = async (req, res) => {
  try {
    const { sampleId, parameterId, value, result } = req.body;

    const data = await qcService.updateQCParameter(
      sampleId,
      parameterId,
      value,
      result,
    );

    res.json({
      success: true,
      message: "QC parameter updated",
      data,
    });
  } catch (err) {
    res.status(500).json({
      success: false,
      message: "Failed to update QC",
    });
  }
};

module.exports = {
  createQCParam,
  getQCParams,
  deleteQCParam,
  updateQCParam,
};
