import { tap, expect } from '@push.rocks/tapbundle';
import * as getInvoices from './assets/getasset.js';
import { ValidatorFactory } from '../ts/formats/validator.factory.js';
import { ValidationLevel } from '../ts/interfaces.js';
import { validateXml } from '../ts/index.js';

// Test ValidatorFactory format detection
tap.test('ValidatorFactory should detect UBL format', async () => {
  const path = getInvoices.invoices.XMLRechnung.UBL['EN16931_Einfach.ubl.xml'];
  const invoice = await getInvoices.getInvoice(path);
  const xml = invoice.toString('utf8');
  
  const validator = ValidatorFactory.createValidator(xml);
  expect(validator.constructor.name).toBeTypeOf('string');
  expect(validator.constructor.name).toInclude('UBL');
});

tap.test('ValidatorFactory should detect CII/Factur-X format', async () => {
  const path = getInvoices.invoices.XMLRechnung.CII['EN16931_Einfach.cii.xml'];
  const invoice = await getInvoices.getInvoice(path);
  const xml = invoice.toString('utf8');
  
  const validator = ValidatorFactory.createValidator(xml);
  expect(validator.constructor.name).toBeTypeOf('string');
  expect(validator.constructor.name).toInclude('FacturX');
});

// Test UBL validation
tap.test('UBL validator should validate valid XML at syntax level', async () => {
  const path = getInvoices.invoices.XMLRechnung.UBL['EN16931_Einfach.ubl.xml'];
  const invoice = await getInvoices.getInvoice(path);
  const xml = invoice.toString('utf8');
  
  const result = validateXml(xml, ValidationLevel.SYNTAX);
  expect(result.valid).toBeTrue();
  expect(result.errors.length).toEqual(0);
});

// Test CII validation
tap.test('CII validator should validate valid XML at syntax level', async () => {
  const path = getInvoices.invoices.XMLRechnung.CII['EN16931_Einfach.cii.xml'];
  const invoice = await getInvoices.getInvoice(path);
  const xml = invoice.toString('utf8');
  
  const result = validateXml(xml, ValidationLevel.SYNTAX);
  expect(result.valid).toBeTrue();
  expect(result.errors.length).toEqual(0);
});

// Test XInvoice integration
tap.test('XInvoice class should validate invoices on load when requested', async () => {
  // Import XInvoice dynamically to prevent circular dependencies
  const { XInvoice } = await import('../ts/index.js');
  const invoice = new XInvoice();
  
  // Load a UBL invoice with validation
  const path = getInvoices.invoices.XMLRechnung.UBL['EN16931_Einfach.ubl.xml'];
  const invoiceBuffer = await getInvoices.getInvoice(path);
  const xml = invoiceBuffer.toString('utf8');
  
  // Add XML with validation enabled
  await invoice.addXmlString(xml, true);
  
  // Check validation results
  expect(invoice.isValid()).toBeTrue();
  expect(invoice.getValidationErrors().length).toEqual(0);
});

// Mark the test file as complete
tap.start();