import { tap, expect } from '@push.rocks/tapbundle';
import { XInvoice } from '../ts/classes.xinvoice.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('XInvoice 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 XInvoice from XML
      const xinvoice = await XInvoice.fromXml(xmlContent);
      
      // Check that the XInvoice instance has the expected properties
      if (xinvoice && xinvoice.from && xinvoice.to && xinvoice.items) {
        console.log('✅ Success: File loaded and parsed successfully');
        console.log(`Format: ${xinvoice.getFormat()}`);
        console.log(`From: ${xinvoice.from.name}`);
        console.log(`To: ${xinvoice.to.name}`);
        console.log(`Items: ${xinvoice.items.length}`);
        
        // Try to export the invoice back to XML
        try {
          let exportFormat = 'facturx';
          if (xinvoice.getFormat() === InvoiceFormat.UBL || xinvoice.getFormat() === InvoiceFormat.XRECHNUNG) {
            exportFormat = 'xrechnung';
          }
          
          const exportedXml = await xinvoice.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();
