import { describe, expect, it } from 'vitest';

import {
  DETAIL_SECTIONS,
  SECTION_BY_TAB,
  displayValue,
  fmtMoney,
  readContent,
  type DetailField,
} from './detailConfig';

describe('detailConfig schema', () => {
  it('has the five administrative sections in order with unique tab ids', () => {
    expect(DETAIL_SECTIONS.map((s) => s.tab)).toEqual([
      'general',
      'contract',
      'funding',
      'timeline',
      'acceptance',
    ]);
    expect(DETAIL_SECTIONS.map((s) => s.index)).toEqual(['I', 'II', 'III', 'IV', 'V']);
  });

  it('SECTION_BY_TAB resolves every section', () => {
    for (const s of DETAIL_SECTIONS) expect(SECTION_BY_TAB[s.tab]).toBe(s);
  });

  it('field keys are globally unique (no content-key collisions across sections)', () => {
    const keys = DETAIL_SECTIONS.flatMap((s) => s.fields.map((f) => f.key));
    expect(new Set(keys).size).toBe(keys.length);
  });

  it('every select field declares options', () => {
    const selects = DETAIL_SECTIONS.flatMap((s) => s.fields).filter((f) => f.type === 'select');
    expect(selects.length).toBeGreaterThan(0);
    for (const f of selects) expect(f.options && f.options.length).toBeTruthy();
  });

  it('reuses the proposal keys that the BE promotes to columns', () => {
    const keys = new Set(DETAIL_SECTIONS.flatMap((s) => s.fields.map((f) => f.key)));
    for (const k of ['tenDeTai', 'chuNhiem.hoTen', 'tongKinhPhi', 'thoiGianThucHienThang', 'capDeTai']) {
      expect(keys.has(k)).toBe(true);
    }
  });
});

describe('display helpers', () => {
  const money: DetailField = { key: 'x', label: '', type: 'money' };
  const months: DetailField = { key: 'x', label: '', type: 'months' };
  const text: DetailField = { key: 'x', label: '', type: 'text' };

  it('fmtMoney groups vi-VN and appends VNĐ', () => {
    expect(fmtMoney(29900000)).toBe('29.900.000 VNĐ');
    expect(fmtMoney('25600000')).toBe('25.600.000 VNĐ');
    expect(fmtMoney('')).toBe('');
    expect(fmtMoney(0)).toBe('');
    expect(fmtMoney('abc')).toBe('');
  });

  it('displayValue formats by type and returns empty string for blanks', () => {
    expect(displayValue(money, 29900000)).toBe('29.900.000 VNĐ');
    expect(displayValue(months, 24)).toBe('24 tháng');
    expect(displayValue(text, 'Dược')).toBe('Dược');
    expect(displayValue(text, '')).toBe('');
    expect(displayValue(text, null)).toBe('');
    expect(displayValue(text, undefined)).toBe('');
  });
});

describe('readContent', () => {
  it('reads flat dotted keys directly', () => {
    const content = { tenDeTai: 'A', 'chuNhiem.hoTen': 'Lâm', tongKinhPhi: 300 };
    expect(readContent(content, 'chuNhiem.hoTen')).toBe('Lâm');
    expect(readContent(content, 'tongKinhPhi')).toBe(300);
    expect(readContent(content, 'missing')).toBeUndefined();
    expect(readContent(undefined, 'x')).toBeUndefined();
  });
});
