const Prefix = require("../../models/securityops/configurationModel");

/**
 * CREATE PREFIX
 */
const createPrefix = async (req, res) => {
  try {
    const userId = req.user._id;
    const payload = req.body;

    const exists = await Prefix.findOne({
      prefixCode: payload.prefixCode.toUpperCase(),
      isDeleted: false,
    });

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

    const data = await Prefix.create({
      ...payload,
      prefixCode: payload.prefixCode.toUpperCase(),
      currentSequence: payload.sequenceStart || 1,
      createdBy: userId,
      updatedBy: userId,
    });

    res.status(201).json({
      success: true,
      message: "Prefix created successfully",
      data,
    });
  } catch (err) {
    res.status(500).json({ success: false, message: err.message });
  }
};

/**
 * LIST PREFIXES (Pagination + Search)
 */
const getPrefixes = async (req, res) => {
  try {
    const { page = 1, limit = 10, search = "" } = req.query;

    const query = {
      isDeleted: false,
      $or: [
        { moduleName: { $regex: search, $options: "i" } },
        { prefixCode: { $regex: search, $options: "i" } },
      ],
    };

    const data = await Prefix.find(query)
      .sort({ createdAt: -1 })
      .skip((page - 1) * limit)
      .limit(Number(limit));

    const total = await Prefix.countDocuments(query);

    res.json({
      success: true,
      total,
      page: Number(page),
      pages: Math.ceil(total / limit),
      data,
    });
  } catch (err) {
    res.status(500).json({ success: false, message: err.message });
  }
};

/**
 * GET BY ID
 */
const getPrefixById = async (req, res) => {
  try {
    const data = await Prefix.findOne({
      _id: req.params.id,
      isDeleted: false,
    });

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

    res.json({ success: true, data });
  } catch (err) {
    res.status(500).json({ success: false, message: err.message });
  }
};

/**
 * UPDATE PREFIX
 */
const updatePrefix = async (req, res) => {
  try {
    const userId = req.user._id;

    const data = await Prefix.findOneAndUpdate(
      { _id: req.params.id, isDeleted: false },
      {
        ...req.body,
        updatedBy: userId,
      },
      { new: true }
    );

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

    res.json({
      success: true,
      message: "Prefix updated",
      data,
    });
  } catch (err) {
    res.status(500).json({ success: false, message: err.message });
  }
};

/**
 * SOFT DELETE PREFIX
 */
const deletePrefix = async (req, res) => {
  try {
    const userId = req.user._id;

    const data = await Prefix.findByIdAndUpdate(req.params.id, {
      isDeleted: true,
      deletedAt: new Date(),
      deletedBy: userId,
    });

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

    res.json({
      success: true,
      message: "Prefix deleted successfully",
    });
  } catch (err) {
    res.status(500).json({ success: false, message: err.message });
  }
};

/**
 * ATOMIC SEQUENCE GENERATOR (VERY IMPORTANT ERP API)
 */
const generateSequence = async (req, res) => {
  try {
    const { moduleName } = req.body;

    const prefix = await Prefix.findOneAndUpdate(
      { moduleName, isDeleted: false, isActive: true },
      { $inc: { currentSequence: 1 } },
      { new: true }
    );

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

    const number = String(prefix.currentSequence).padStart(
      prefix.paddingLength,
      "0"
    );

    const year = new Date().getFullYear();

    const generated = prefix.yearlyReset
      ? `${prefix.prefixCode}${prefix.separator}${year}${prefix.separator}${number}`
      : `${prefix.prefixCode}${prefix.separator}${number}`;

    res.json({
      success: true,
      generatedNumber: generated,
      sequence: prefix.currentSequence,
    });
  } catch (err) {
    res.status(500).json({ success: false, message: err.message });
  }
};

module.exports = {
    createPrefix,
    getPrefixes,
    getPrefixById,
    updatePrefix,
    deletePrefix,
    generateSequence,

}

