/**
 * Granite Team_Device Loader xlsx generation.
 * Produces a properly formatted xlsx file for upload to SNIP XperLoad.
 */

import * as XLSX from 'xlsx';
import { LOADER_COLUMNS } from './graniteLoaderConfig';

/**
 * Generate a Granite Loader Sheet xlsx file.
 *
 * @param {Object} config
 * @param {string} config.operationType - 'Change' | 'Add' | 'Delete' | 'Move'
 * @param {Array<string>} config.columnIds - selected column IDs (in any order; output uses canonical order)
 * @param {Array<Object>} config.rows - device rows, each keyed by column ID with string values
 * @returns {Blob} xlsx file as a Blob for browser download
 */
export function generateLoaderXlsx(config) {
  const { operationType, columnIds, rows } = config;

  // Filter LOADER_COLUMNS to only selected columns, preserving canonical order
  const selectedColumns = LOADER_COLUMNS.filter(col => columnIds.includes(col.id));

  // Build header row from canonical labels
  const headers = selectedColumns.map(col => col.label);

  // Build data rows
  const dataRows = rows.map(row => {
    return selectedColumns.map(col => {
      // DELETE column auto-fill for Delete operations
      if (col.id === 'DELETE' && operationType === 'Delete') {
        return 'X';
      }

      // Get the value from the row
      let value = row[col.id];

      // EQUIPMENT CLASS defaults to "S" if not explicitly set
      if (col.id === 'EQUIPMENT_CLASS' && (value === undefined || value === null || value === '')) {
        value = 'S';
      }

      // Convert null/undefined to empty string (not "null" or "undefined")
      if (value === null || value === undefined) {
        return '';
      }

      return String(value);
    });
  });

  // Combine headers + data into array-of-arrays
  const aoa = [headers, ...dataRows];

  // Create workbook and worksheet
  const ws = XLSX.utils.aoa_to_sheet(aoa);
  const wb = XLSX.utils.book_new();
  XLSX.utils.book_append_sheet(wb, ws, 'Load_Sheet');

  // Write to array buffer
  const wbOut = XLSX.write(wb, { bookType: 'xlsx', type: 'array' });

  // Return as Blob
  return new Blob([wbOut], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
}

/**
 * Generate a descriptive filename for the loader sheet.
 *
 * @param {string} operationType - 'Change' | 'Add' | 'Delete' | 'Move'
 * @param {string} [teamName] - optional team name to include in filename
 * @returns {string} filename like "Loader_Change_NTS-AEO-STEAM_2026-05-27.xlsx"
 */
export function generateFilename(operationType, teamName) {
  const date = new Date().toISOString().slice(0, 10);
  const parts = ['Loader', operationType];
  if (teamName) {
    parts.push(teamName.replace(/[^a-zA-Z0-9_-]/g, '-'));
  }
  parts.push(date);
  return parts.join('_') + '.xlsx';
}
