import * as XLSX from 'xlsx';

/**
 * Generates and downloads an Excel template file for customer import
 * Includes all customer fields and address fields
 */
export function downloadCustomerTemplate() {
  // Define the headers including address fields
  const headers = [
    'title',
    'first_name',
    'last_name',
    'email',
    'mobile_phone',
    'home_phone',
    'id',
    'iso',
    'assigned_to_id',
    'address1',
    'address2',
    'town_city',
    'county',
    'country',
    'post_code',
    'primary',
    'formatted_address'
  ];

  // Create sample data row (for reference)
  const sampleData = [
    {
      title: '',
      first_name: '',
      last_name: '',
      email: '',
      mobile_phone: '',
      home_phone: '',
      id: '',
      iso: '',
      assigned_to_id: '',
      address1: '',
      address2: '',
      town_city: '',
      county: '',
      country: '',
      post_code: '',
      primary: true,
      formatted_address: ''
    }
  ];

  // Create workbook
  const workbook = XLSX.utils.book_new();

  // Create worksheet with headers and sample data
  const worksheetData = [
    headers, // First row: headers
    ...sampleData.map(row => headers.map(header => {
      const value = row[header as keyof typeof row];
      if (value === undefined || value === null) return '';
      return value;
    })) // Sample data rows
  ];

  const worksheet = XLSX.utils.aoa_to_sheet(worksheetData);

  // Set column widths for better readability
  worksheet['!cols'] = [
    { wch: 15 }, // id
    { wch: 15 }, // first_name
    { wch: 15 }, // last_name
    { wch: 30 }, // email
    { wch: 15 }, // mobile_phone
    { wch: 15 }, // home_phone
    { wch: 10 }, // title
    { wch: 10 }, // iso
    { wch: 15 }, // assigned_to_id
    { wch: 25 }, // address1
    { wch: 25 }, // address2
    { wch: 20 }, // town_city
    { wch: 20 }, // county
    { wch: 20 }, // country
    { wch: 12 }, // post_code
    { wch: 8 },  // primary
    { wch: 80 }, // formatted_address
  ];

  // Add worksheet to workbook
  XLSX.utils.book_append_sheet(workbook, worksheet, 'Customers');

  // Generate file name with timestamp
  const fileName = `customer_import_template_${new Date().toISOString().split('T')[0]}.xlsx`;

  // Write and download file
  XLSX.writeFile(workbook, fileName);
}










