/**
 * ID Formatter Utility
 * Transforms numeric database IDs into human-readable formatted IDs
 * WITHOUT modifying the database schema
 */

const ID_PREFIXES = {
  deviations: "DV",
  "case-investigations": "CS",
  "site-monitoring": "SM",
  sds: "SDS",
  "toolbox-talk": "TT",
  "job-safety-analysis": "JSA",
  "risk-assessment": "RA",
  "pre-task-checklist": "CH",
  "equipment-control": "EQ",
  "minutes-of-meeting": "mom",
  "permit-to-work": "PTW",
  training: "TRN",
  companies: "EHS",
  "hazop-study": "HZP",
  "hazid-study": "HZD",
};

/**
 * Format a numeric ID with entity-specific prefix and zero-padding
 * @param {string} entityType - The type of entity (e.g., 'deviations', 'sds')
 * @param {number} rawId - The numeric database ID
 * @returns {string} Formatted ID (e.g., 'DV-001', 'SDS-042')
 */
const formatId = (entityType, rawId) => {
  if (!rawId) return null;

  const prefix = ID_PREFIXES[entityType];
  if (!prefix) {
    console.warn(`Unknown entity type: ${entityType}. Returning raw ID.`);
    return String(rawId);
  }

  // Zero-pad to at least 3 digits, but expand naturally for larger numbers
  const paddedId = String(rawId).padStart(3, "0");
  return `${prefix}-${paddedId}`;
};

/**
 * Add formatted ID to a single entity object
 * @param {string} entityType - The type of entity
 * @param {Object} entity - The entity object from database
 * @returns {Object} Entity with added formattedId field
 */
const addFormattedId = (entityType, entity) => {
  if (!entity) return entity;

  // Handle Sequelize model instances
  const plainEntity = entity.toJSON ? entity.toJSON() : entity;

  return {
    ...plainEntity,
    formattedId: formatId(entityType, plainEntity.id),
  };
};

/**
 * Add formatted IDs to an array of entities
 * @param {string} entityType - The type of entity
 * @param {Array} entities - Array of entity objects from database
 * @returns {Array} Entities with added formattedId field
 */
const addFormattedIds = (entityType, entities) => {
  if (!Array.isArray(entities)) return entities;

  return entities.map((entity) => addFormattedId(entityType, entity));
};

/**
 * Middleware to automatically add formatted IDs to response
 * Usage: router.get('/deviations', formatIdMiddleware('deviations'), controller)
 */
const formatIdMiddleware = (entityType) => {
  return (req, res, next) => {
    const originalJson = res.json.bind(res);

    res.json = (data) => {
      if (Array.isArray(data)) {
        return originalJson(addFormattedIds(entityType, data));
      } else if (data && typeof data === "object") {
        return originalJson(addFormattedId(entityType, data));
      }
      return originalJson(data);
    };

    next();
  };
};

module.exports = {
  formatId,
  addFormattedId,
  addFormattedIds,
  formatIdMiddleware,
  ID_PREFIXES,
};
