export const BOOK_TYPES = ['GAAP', 'FEDERAL', 'STATE', 'AMT', 'ACE', 'USER'];

export function makeDefaultBooks(asset = {}, codes = BOOK_TYPES) {
  return (codes && codes.length ? codes : BOOK_TYPES).map((bookType) => ({
    book_type: bookType,
    active: bookType === 'GAAP' || bookType === 'FEDERAL',
    cost: null,
    depreciation_method: asset.depreciation_method || 'straight_line',
    convention: 'half_year',
    useful_life_months: asset.useful_life_months || 60,
    section_179_amount: 0,
    bonus_percent: 0,
    business_use_percent: 100,
    investment_use_percent: 0
  }));
}

// Merge an asset's saved books with the currently-enabled book codes: keep existing
// values, add defaults for newly-enabled books, and preserve any extra saved books.
export function mergeBooks(existing = [], codes = BOOK_TYPES, asset = {}) {
  const byType = Object.fromEntries((existing || []).map((book) => [book.book_type, book]));
  const defaults = makeDefaultBooks(asset, codes);
  const merged = (codes && codes.length ? codes : BOOK_TYPES).map(
    (code) => byType[code] || defaults.find((d) => d.book_type === code)
  );
  for (const book of existing || []) {
    if (!merged.some((b) => b.book_type === book.book_type)) merged.push(book);
  }
  return merged;
}

export function blankAsset() {
  const today = new Date().toISOString().slice(0, 10);
  const base = {
    asset_id: '',
    entity_id: null,
    description: '',
    category: 'Computer Equipment',
    status: 'in_service',
    acquisition_cost: 0,
    acquired_date: today,
    in_service_date: today,
    useful_life_months: 60,
    salvage_value: 0,
    land_value: 0,
    prior_depreciation: 0,
    depreciation_method: 'straight_line',
    location: '',
    department: '',
    group_name: '',
    custodian: '',
    vendor: '',
    serial_number: '',
    invoice_number: '',
    gl_asset_account: '',
    gl_expense_account: '',
    gl_accumulated_account: '',
    barcode_value: '',
    condition: '',
    new_or_used: 'new',
    special_zone: '',
    listed_property: false,
    business_use_percent: 100,
    investment_use_percent: 0,
    notes: '',
    custom_fields: {}
  };
  base.books = makeDefaultBooks(base);
  return base;
}

export function slugFieldKey(value) {
  return String(value || '')
    .trim()
    .toLowerCase()
    .replace(/[^a-z0-9]+/g, '_')
    .replace(/^_+|_+$/g, '');
}

export function normalizeCustomFields(fields) {
  return (fields || [])
    .map((field) => ({
      key: slugFieldKey(field.key || field.label),
      label: field.label || field.key || 'Custom field',
      type: ['text', 'date', 'bool', 'numeric'].includes(field.type) ? field.type : 'text',
      required: Boolean(field.required),
      defaultValue: field.defaultValue ?? field.default ?? ''
    }))
    .filter((field) => field.key);
}

export function defaultValueForField(field) {
  if (field.defaultValue !== undefined && field.defaultValue !== null && field.defaultValue !== '') {
    if (field.type === 'bool') return Boolean(field.defaultValue);
    if (field.type === 'numeric') return Number(field.defaultValue);
    return field.defaultValue;
  }
  if (field.type === 'bool') return false;
  return '';
}

export function inputTypeForCustomField(field) {
  if (field.type === 'numeric') return 'number';
  if (field.type === 'date') return 'date';
  return 'text';
}
