import { describe, expect, it, mock } from 'bun:test';
import { createResearchCaptureController } from './useResearchCaptureFlow';
import type { ResearchComposerState } from './useResearchComposer';

const baseDraft: ResearchComposerState = {
  rawText: 'Demand is stabilizing.',
  ticker: 'NVDA',
  workspaceId: '',
  sourceUrl: '',
  sourceTitle: '',
  sourceKind: 'manual',
  userNoteTypeOverride: 'claim',
  includeCurrentContext: true,
};

describe('createResearchCaptureController', () => {
  it('auto-creates a workspace from ticker context before capturing', async () => {
    const ensureWorkspace = mock(async () => ({
      id: 'workspace-1',
      name: 'NVDA Research',
      primaryTicker: 'NVDA',
      scope: 'single_company' as const,
      stage: 'capture' as const,
      defaultView: 'canvas' as const,
      pinnedNoteIds: [],
      archived: false,
      createdAt: '2026-04-09T10:00:00Z',
      updatedAt: '2026-04-09T10:00:00Z',
    }));
    const captureRequest = mock(async (request) => ({
      note: {
        id: 'note-1',
        workspaceId: request.workspaceId,
      },
      placementHint: {
        tileLane: 'normal',
        kanbanColumn: 'claim',
      },
      queuedJobs: [],
    }));

    const captureNote = createResearchCaptureController({
      ensureWorkspace,
      captureNoteRequest: captureRequest as never,
    });

    const result = await captureNote({
      draft: baseDraft,
      fallbackTicker: 'NVDA',
      autoCreateFromTicker: true,
    });

    expect(ensureWorkspace).toHaveBeenCalledWith({
      workspaceId: undefined,
      ticker: 'NVDA',
    });
    expect(captureRequest).toHaveBeenCalledTimes(1);
    expect(captureRequest).toHaveBeenCalledWith({
      workspaceId: 'workspace-1',
      rawText: 'Demand is stabilizing.',
      ticker: 'NVDA',
      userNoteTypeOverride: 'claim',
      sourceRef: undefined,
    });
    expect(result.note.workspaceId).toBe('workspace-1');
  });

  it('blocks submission when no workspace can be resolved', async () => {
    const captureNote = createResearchCaptureController({
      ensureWorkspace: async () => null,
    });

    await expect(
      captureNote({
        draft: { ...baseDraft, ticker: '', rawText: 'Need follow-up' },
        autoCreateFromTicker: false,
      }),
    ).rejects.toThrow('Select or create a research workspace');
  });
});
