import { tap, expect } from '@git.zone/tstest/tapbundle';
import { EInvoice } from '../ts/einvoice.js';
import { InvoiceFormat } from '../ts/interfaces/common.js';
import * as fs from 'fs/promises';
import * as path from 'path';

// Test a simple subset of corpus files
tap.test('EInvoice should handle a simple subset of corpus files', async () => {
  // Test a few specific files that we know work
  const testFiles = [
    // CII files
    path.join(process.cwd(), 'test/assets/corpus/XML-Rechnung/CII/EN16931_Einfach.cii.xml'),
    // UBL files
    path.join(process.cwd(), 'test/assets/corpus/XML-Rechnung/UBL/EN16931_Einfach.ubl.xml'),
    // PEPPOL files (if available)
    path.join(process.cwd(), 'test/assets/corpus/PEPPOL/peppol-bis-invoice-3-sample.xml')
  ];
  
  // Test each file
  for (const file of testFiles) {
    try {
      console.log(`\nTesting file: ${path.basename(file)}`);
      
      // Check if file exists
      try {
        await fs.access(file);
      } catch (error) {
        console.log(`File not found: ${file}`);
        continue;
      }
      
      // Read the file
      const xmlContent = await fs.readFile(file, 'utf8');
      
      // Create EInvoice from XML
      const einvoice = await EInvoice.fromXml(xmlContent);
      
      // Check that the EInvoice instance has the expected properties
      if (einvoice && einvoice.from && einvoice.to && einvoice.items) {
        console.log('✅ Success: File loaded and parsed successfully');
        console.log(`Format: ${einvoice.getFormat()}`);
        console.log(`From: ${einvoice.from.name}`);
        console.log(`To: ${einvoice.to.name}`);
        console.log(`Items: ${einvoice.items.length}`);
        
        // Try to export the invoice back to XML
        try {
          let exportFormat = 'facturx';
          if (einvoice.getFormat() === InvoiceFormat.UBL || einvoice.getFormat() === InvoiceFormat.XRECHNUNG) {
            exportFormat = 'xrechnung';
          }
          
          const exportedXml = await einvoice.exportXml(exportFormat as any);
          
          if (exportedXml) {
            console.log('✅ Successfully exported back to XML');
            
            // Save the exported XML for inspection
            const testDir = path.join(process.cwd(), 'test', 'output', 'simple');
            await fs.mkdir(testDir, { recursive: true });
            await fs.writeFile(path.join(testDir, `${path.basename(file)}-exported.xml`), exportedXml);
          } else {
            console.log('❌ Failed to export valid XML');
          }
        } catch (exportError) {
          console.log(`❌ Export error: ${exportError.message}`);
        }
      } else {
        console.log('❌ Missing required properties');
      }
    } catch (error) {
      console.log(`❌ Error processing the file: ${error.message}`);
    }
  }
  
  // Success - we're just testing individual files
  expect(true).toBeTrue();
});

// Run the tests
tap.start();