const cleanIsbnInput = (value = '') => value.replace(/[^0-9Xx]/g, '').toUpperCase();

const isIsbn13 = (value) => /^\d{13}$/.test(value);
const isIsbn10 = (value) => /^\d{9}[\dX]$/.test(value);

const computeIsbn13CheckDigit = (twelveDigits) => {
  const sum = twelveDigits
    .split('')
    .reduce((acc, digit, index) => {
      const weight = index % 2 === 0 ? 1 : 3;
      return acc + parseInt(digit, 10) * weight;
    }, 0);
  const mod = sum % 10;
  return mod === 0 ? '0' : String(10 - mod);
};

const convertIsbn10To13 = (isbn10) => {
  const core = isbn10.slice(0, 9);
  const base = `978${core}`;
  const checkDigit = computeIsbn13CheckDigit(base);
  return base + checkDigit;
};

const normalizeIsbnForLookup = (value) => {
  const cleaned = cleanIsbnInput(value);

  if (isIsbn13(cleaned)) {
    return cleaned;
  }

  if (/^\d{10}$/.test(cleaned)) {
    return cleaned;
  }

  if (isIsbn10(cleaned)) {
    return convertIsbn10To13(cleaned);
  }

  const error = new Error('ISBN formati hatali. 10 veya 13 haneli olmali.');
  error.status = 400;
  throw error;
};

module.exports = {
  cleanIsbnInput,
  normalizeIsbnForLookup
};
