import { describe, it, expect } from 'vitest';
import { Brief, LetterBlock, allDiagnostics, canSubmit, hasBlockingErrors, unresolvedPlaceholders } from './brief';
import { PlaceholderDef } from './placeholders';
import { RichTextBlock } from '@shared/kernel/rich-text';

const placeholders: PlaceholderDef[] = [
  { key: 'naam', label: 'Naam', autoResolvable: true },
  { key: 'reden', label: 'Reden', autoResolvable: false },
];

const content = (...keys: string[]): RichTextBlock => ({
  paragraphs: [{ nodes: keys.map((key) => ({ type: 'placeholder', key })) }],
});

const passage = (blockId: string, ...keys: string[]): LetterBlock => ({
  type: 'freeText',
  blockId,
  content: content(...keys),
});

function brief(sections: Brief['sections']): Brief {
  return { briefId: 'b1', beroep: 'arts', templateId: 't1', placeholders, sections, status: { tag: 'draft' }, drafterId: 'u1' };
}

describe('brief selectors', () => {
  it('unresolvedPlaceholders returns deduped manual keys only (auto excluded)', () => {
    const b = brief([
      { sectionKey: 's1', title: 'S1', required: true, locked: false, blocks: [passage('local-1', 'naam', 'reden')] },
      { sectionKey: 's2', title: 'S2', required: false, locked: false, blocks: [passage('local-2', 'reden')] },
    ]);
    expect(unresolvedPlaceholders(b)).toEqual(['reden']); // 'naam' is auto; 'reden' deduped
  });

  it('allDiagnostics flattens across sections and blocks', () => {
    const b = brief([
      { sectionKey: 's1', title: 'S1', required: true, locked: false, blocks: [passage('local-1', 'reden', 'onbekend')] },
    ]);
    const codes = allDiagnostics(b).map((d) => d.code);
    expect(codes).toContain('unresolved-at-send'); // reden
    expect(codes).toContain('unknown-placeholder'); // onbekend
    expect(hasBlockingErrors(allDiagnostics(b))).toBe(true); // unknown is an error
  });

  it('canSubmit is false when a required section is empty, true otherwise', () => {
    expect(canSubmit(brief([{ sectionKey: 's1', title: 'S1', required: true, locked: false, blocks: [] }]))).toBe(false);
    expect(canSubmit(brief([{ sectionKey: 's1', title: 'S1', required: false, locked: false, blocks: [] }]))).toBe(true);
    expect(canSubmit(brief([{ sectionKey: 's1', title: 'S1', required: true, locked: false, blocks: [passage('local-1')] }]))).toBe(true);
  });
});
