import { describe, it, expect } from 'vitest';
import { renderTemplate } from '../lib/template-engine.js';

describe('renderTemplate', () => {
  it('replaces simple variables', () => {
    const result = renderTemplate('Hello {{NAME}}!', { NAME: 'World' });
    expect(result).toBe('Hello World!');
  });

  it('replaces multiple variables', () => {
    const result = renderTemplate('{{A}} and {{B}}', { A: 'foo', B: 'bar' });
    expect(result).toBe('foo and bar');
  });

  it('replaces numeric variables', () => {
    const result = renderTemplate('Port: {{PORT}}', { PORT: 4017 });
    expect(result).toBe('Port: 4017');
  });

  it('leaves unknown variables intact', () => {
    const result = renderTemplate('{{KNOWN}} {{UNKNOWN}}', { KNOWN: 'yes' });
    expect(result).toBe('yes {{UNKNOWN}}');
  });

  it('includes IF block when truthy', () => {
    const result = renderTemplate('{{#IF HAS_WEB}}web here{{/IF HAS_WEB}}', { HAS_WEB: true });
    expect(result).toBe('web here');
  });

  it('excludes IF block when falsy', () => {
    const result = renderTemplate('before{{#IF HAS_WEB}}web here{{/IF HAS_WEB}}after', {
      HAS_WEB: false,
    });
    expect(result).toBe('beforeafter');
  });

  it('includes UNLESS block when falsy', () => {
    const result = renderTemplate('{{#UNLESS HAS_WEB}}no web{{/UNLESS HAS_WEB}}', {
      HAS_WEB: false,
    });
    expect(result).toBe('no web');
  });

  it('excludes UNLESS block when truthy', () => {
    const result = renderTemplate('{{#UNLESS HAS_WEB}}no web{{/UNLESS HAS_WEB}}', {
      HAS_WEB: true,
    });
    expect(result).toBe('');
  });

  it('handles nested variables inside IF blocks', () => {
    const result = renderTemplate('{{#IF HAS_WEB}}Port: {{PORT}}{{/IF HAS_WEB}}', {
      HAS_WEB: true,
      PORT: 3000,
    });
    expect(result).toBe('Port: 3000');
  });

  it('handles multiline IF blocks', () => {
    const tmpl = `start
{{#IF HAS_BACKEND}}backend line 1
backend line 2
{{/IF HAS_BACKEND}}end`;
    const result = renderTemplate(tmpl, { HAS_BACKEND: true });
    expect(result).toContain('backend line 1');
    expect(result).toContain('backend line 2');
    expect(result).toContain('start');
    expect(result).toContain('end');
  });

  it('handles multiple IF blocks', () => {
    const tmpl = '{{#IF A}}aaa{{/IF A}}|{{#IF B}}bbb{{/IF B}}';
    expect(renderTemplate(tmpl, { A: true, B: false })).toBe('aaa|');
    expect(renderTemplate(tmpl, { A: false, B: true })).toBe('|bbb');
    expect(renderTemplate(tmpl, { A: true, B: true })).toBe('aaa|bbb');
  });
});
