import assert from 'node:assert';
import { test } from 'node:test';
import { compileManuscriptToBookHtml, resolveWikilinks } from '@book-print/markdown';
import { canTransitionOrder, assertValidOrderTransition } from '@book-print/shared';
import { MockPrintProvider } from '@book-print/printer';
import { BOOK_6X9_PRINT_OPTIONS } from '@book-print/pdf';

test('Wikilink Parsing', () => {
  const result = resolveWikilinks('Check [[My Note]] and [[Chapter One|Introduction]] and ![[image.png]]');
  assert.strictEqual(result, 'Check My Note and Introduction and ![image.png](image.png)');
});

test('Markdown Compilation & Page Breaks (///)', () => {
  const manuscript = `# Chapter 1\n\nSome text...\n\n///\n\n# Chapter 2\n\nNext text...`;
  const html = compileManuscriptToBookHtml(manuscript, {
    metadata: {
      title: 'Test Book',
      author: 'Test Author',
      includeTitlePage: true,
      includeCopyrightPage: false,
    },
  });

  assert.ok(html.includes('<h1 class="book-h1">Chapter 1</h1>'));
  assert.ok(html.includes('<div class="book-page-break"></div>'));
  assert.ok(html.includes('<h1 class="book-h1">Chapter 2</h1>'));
  assert.ok(html.includes('<h1 class="book-main-title">Test Book</h1>'));
});

test('Electron 6x9 PDF Micron Page Dimensions', () => {
  assert.strictEqual(BOOK_6X9_PRINT_OPTIONS.pageSize.width, 152400); // 6 inches in microns
  assert.strictEqual(BOOK_6X9_PRINT_OPTIONS.pageSize.height, 228600); // 9 inches in microns
  assert.strictEqual(BOOK_6X9_PRINT_OPTIONS.marginsType, 0);
});

test('Order State Machine Transitions', () => {
  assert.strictEqual(canTransitionOrder('draft', 'rendering'), true);
  assert.strictEqual(canTransitionOrder('rendered', 'validating'), true);
  assert.strictEqual(canTransitionOrder('quoted', 'awaiting_payment'), true);
  assert.strictEqual(canTransitionOrder('paid', 'submitting_to_printer'), true);
  assert.strictEqual(canTransitionOrder('delivered', 'draft'), false);
  assert.throws(() => assertValidOrderTransition('delivered', 'draft'));
});

test('Mock Printer Quote & Order Creation', async () => {
  const provider = new MockPrintProvider();
  const address = {
    fullName: 'Joseph Rastovich',
    addressLine1: '123 Main St',
    city: 'White Salmon',
    state: 'WA',
    postalCode: '98672',
    country: 'US',
  };

  const quote = await provider.getQuote({
    projectId: 'test-proj-1',
    pageCount: 100,
    binding: 'paperback',
    quantity: 1,
    shippingAddress: address,
  });

  assert.ok(quote.totalCostCents > 0);
  assert.strictEqual(quote.binding, 'paperback');

  const order = await provider.createOrder({
    projectId: 'test-proj-1',
    quoteId: quote.quoteId,
    interiorPdfUrl: 'https://example.com/interior.pdf',
    coverPdfUrl: 'https://example.com/cover.pdf',
    shippingAddress: address,
    idempotencyKey: 'idempotency-123',
  });

  assert.strictEqual(order.status, 'printer_accepted');
});
