'use strict';

const crypto = require('crypto');

const DEFAULT_MAX_NAME_LENGTH = 30;
const HASH_LENGTH = 7;

function generateConstraintName(prefix, table, suffix, maxLength) {
  const limit = typeof maxLength === 'number' && maxLength > 0 ? maxLength : DEFAULT_MAX_NAME_LENGTH;
  const original = (suffix === undefined || suffix === null || suffix === '')
    ? `${prefix}_${table}`
    : `${prefix}_${table}_${suffix}`;

  if (original.length <= limit) {
    return original;
  }

  const prefixLength = limit - HASH_LENGTH - 1;
  const hash = crypto.createHash('md5').update(original).digest('hex').slice(0, HASH_LENGTH);
  return `${original.slice(0, prefixLength)}_${hash}`;
}

function deriveCompositeShortName(columns, maxLength) {
  if (!Array.isArray(columns) || columns.length === 0) {
    throw new Error('Columns must be a non-empty array');
  }

  const limit = typeof maxLength === 'number' && maxLength > 0 ? maxLength : DEFAULT_MAX_NAME_LENGTH;
  const joined = columns.join('_');
  if (joined.length <= limit) {
    return joined;
  }

  return columns[columns.length - 1];
}

function shortenIdentifier(name, maxLength) {
  const limit = typeof maxLength === 'number' && maxLength > 0 ? maxLength : DEFAULT_MAX_NAME_LENGTH;
  if (name.length <= limit) return name;
  const prefixLength = limit - HASH_LENGTH - 1;
  const hash = crypto.createHash('md5').update(name).digest('hex').slice(0, HASH_LENGTH);
  return `${name.slice(0, prefixLength)}_${hash}`;
}

module.exports = {
  generateConstraintName,
  deriveCompositeShortName,
  shortenIdentifier,
  DEFAULT_MAX_NAME_LENGTH
};
