import { describe, expect, it } from 'bun:test';
import { renderToStaticMarkup } from 'react-dom/server';
import {
  buildFilingsCommand,
  buildFilingsPageSizeCommand,
  buildFilingsPaginationCommand,
  buildFilingsSearchCommand,
  FilingsPanel,
} from './FilingsPanel';
import type { FilingsPanelData } from '../../types/financial';

const samplePanel: FilingsPanelData = {
  symbol: 'AAPL',
  companyName: 'Apple Inc.',
  cik: '0000320193',
  items: [
    {
      accessionNumber: '0000320193-25-000010',
      filingDate: '2025-02-01',
      reportDate: '2024-12-31',
      form: '10-K',
      primaryDocument: 'annual.htm',
      filingUrl:
        'https://www.sec.gov/Archives/edgar/data/320193/000032019325000010/annual.htm',
      overview: 'Annual report',
    },
    {
      accessionNumber: '0000320193-25-000001',
      filingDate: '2025-01-03',
      form: '8-K',
      primaryDocument: '',
      filingUrl: 'https://www.sec.gov/Archives/edgar/data/320193/000032019325000001/',
      overview: 'Current report',
    },
  ],
  page: 2,
  pageSize: 50,
  totalResults: 87,
  totalPages: 2,
  query: '10-K',
  latestFiling: {
    accessionNumber: '0000320193-25-000010',
    filingDate: '2025-02-01',
    reportDate: '2024-12-31',
    form: '10-K',
    primaryDocument: 'annual.htm',
    filingUrl:
      'https://www.sec.gov/Archives/edgar/data/320193/000032019325000010/annual.htm',
    overview: 'Annual report',
  },
};

describe('FilingsPanel', () => {
  it('renders pagination controls and filing rows', () => {
    const html = renderToStaticMarkup(<FilingsPanel data={samplePanel} />);

    expect(html).toContain('Metadata search');
    expect(html).toContain('Previous');
    expect(html).toContain('Next');
    expect(html).toContain('annual.htm');
    expect(html).toContain('Filing directory');
    expect(html).toContain('Current report');
    expect(html).toContain('Open');
  });

  it('builds canonical filings commands with ordered flags', () => {
    expect(
      buildFilingsCommand({
        symbol: 'nvda',
        page: 2,
        pageSize: 50,
        query: 'annual report',
      }),
    ).toBe('/filings NVDA --page 2 --page-size 50 --query "annual report"');
  });

  it('builds pagination commands that preserve page size and search state', () => {
    expect(buildFilingsPaginationCommand(samplePanel, 1)).toBe(
      '/filings AAPL --page-size 50 --query 10-K',
    );
  });

  it('builds page size commands that reset to the first page', () => {
    expect(buildFilingsPageSizeCommand(samplePanel, 100)).toBe(
      '/filings AAPL --page-size 100 --query 10-K',
    );
  });

  it('builds search apply and clear commands with a reset page', () => {
    expect(buildFilingsSearchCommand(samplePanel, 'annual report')).toBe(
      '/filings AAPL --page-size 50 --query "annual report"',
    );
    expect(buildFilingsSearchCommand({ ...samplePanel, pageSize: 25 }, undefined)).toBe(
      '/filings AAPL',
    );
  });
});
