export function blankAsset() {
  const today = new Date().toISOString().slice(0, 10);
  return {
    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,
    depreciation_method: 'straight_line',
    location: '',
    department: '',
    custodian: '',
    vendor: '',
    serial_number: '',
    invoice_number: '',
    gl_asset_account: '',
    gl_expense_account: '',
    notes: '',
    custom_fields: {}
  };
}

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';
}
