const { all, audit, now, one, run } = require('../db');

// Short tax years (IRS Pub 946): when a company's tax year is shorter than 12 months, that year's MACRS
// depreciation is prorated. This is the simplified proration — the year's deduction is multiplied by
// (months ÷ 12); it is most accurate for the placed-in-service (first) short year. Per company + year,
// cached for the engine and invalidated on edits.

const cache = new Map(); // `${entityId}|${year}` -> fraction

function clearCache() {
  cache.clear();
}

// Proration fraction (0–1) for a company's tax year; 1 when the year is a normal 12-month year.
function fraction(entityId, year) {
  if (!entityId || !year) return 1;
  const key = `${entityId}|${Number(year)}`;
  if (cache.has(key)) return cache.get(key);
  const row = one('SELECT months FROM short_tax_years WHERE entity_id = ? AND tax_year = ?', [entityId, Number(year)]);
  const months = row ? Math.max(0, Math.min(12, Number(row.months) || 12)) : 12;
  const f = months / 12;
  cache.set(key, f);
  return f;
}

function list(companyId) {
  return all('SELECT * FROM short_tax_years WHERE entity_id = ? ORDER BY tax_year DESC', [companyId]);
}

function save(companyId, body, userId) {
  const taxYear = Math.trunc(Number(body.tax_year)) || 0;
  if (!taxYear) throw Object.assign(new Error('A valid tax year is required'), { status: 400 });
  const months = Math.max(1, Math.min(12, Number(body.months) || 12));
  run(
    `INSERT INTO short_tax_years (entity_id, tax_year, months, note, updated_by, updated_at)
     VALUES (?, ?, ?, ?, ?, ?)
     ON CONFLICT(entity_id, tax_year) DO UPDATE SET months = excluded.months, note = excluded.note,
       updated_by = excluded.updated_by, updated_at = excluded.updated_at`,
    [companyId, taxYear, months, body.note || null, userId, now()]
  );
  clearCache();
  audit(userId, 'update', 'short_tax_year', `${companyId}:${taxYear}`, null, { tax_year: taxYear, months });
  return one('SELECT * FROM short_tax_years WHERE entity_id = ? AND tax_year = ?', [companyId, taxYear]);
}

function remove(companyId, taxYear, userId) {
  const before = one('SELECT * FROM short_tax_years WHERE entity_id = ? AND tax_year = ?', [companyId, Number(taxYear)]);
  if (!before) return false;
  run('DELETE FROM short_tax_years WHERE entity_id = ? AND tax_year = ?', [companyId, Number(taxYear)]);
  clearCache();
  audit(userId, 'delete', 'short_tax_year', `${companyId}:${taxYear}`, before, null);
  return true;
}

module.exports = { clearCache, fraction, list, remove, save };
