import type { CsvParsedFile, CsvPreviewError } from './types';

function issue(
  file: string,
  column: string,
  code: string,
  message: string,
  suggestedFix: string
): CsvPreviewError {
  return { file, row: 1, column, code, message, suggestedFix };
}

export function validateCsvHeaders(file: CsvParsedFile): CsvPreviewError[] {
  const errors: CsvPreviewError[] = [];
  const seen = new Map<string, number>();

  file.headers.forEach((header, index) => {
    const previousIndex = seen.get(header);
    if (previousIndex !== undefined) {
      errors.push(
        issue(
          file.fileName,
          header,
          'DUPLICATE_COLUMN',
          `Column "${header}" appears more than once.`,
          `Remove the duplicate column at position ${index + 1}; keep the official template order.`
        )
      );
    }
    seen.set(header, index);
  });

  file.template.expectedHeaders.forEach((expectedHeader, index) => {
    if (!file.headers.includes(expectedHeader)) {
      errors.push(
        issue(
          file.fileName,
          expectedHeader,
          'MISSING_COLUMN',
          `Required template column "${expectedHeader}" is missing.`,
          'Download the latest setup CSV template and keep all official columns.'
        )
      );
      return;
    }

    if (file.headers[index] !== expectedHeader) {
      errors.push(
        issue(
          file.fileName,
          expectedHeader,
          'HEADER_ORDER_MISMATCH',
          `Column "${expectedHeader}" is not in the expected position ${index + 1}.`,
          'Reorder columns to match the official template exactly.'
        )
      );
    }
  });

  file.headers.forEach((header) => {
    if (!file.template.expectedHeaders.includes(header)) {
      errors.push(
        issue(
          file.fileName,
          header,
          'EXTRA_COLUMN',
          `Column "${header}" is not part of the official template.`,
          'Remove extra columns before previewing the import.'
        )
      );
    }
  });

  return errors;
}
