import { useCallback } from 'react';
import { researchBridge } from '../lib/researchBridge';
import type {
  NoteCaptureResult,
  ResearchWorkspace,
  SourceReferenceInput,
} from '../types/research';
import type { ResearchComposerState } from './useResearchComposer';

interface EnsureWorkspaceRequest {
  ticker?: string;
  workspaceId?: string | null;
}

export interface CaptureNoteArgs {
  draft: ResearchComposerState;
  fallbackTicker?: string;
  explicitWorkspaceId?: string | null;
  autoCreateFromTicker?: boolean;
}

export interface ResearchCaptureControllerDependencies {
  ensureWorkspace: (
    request: EnsureWorkspaceRequest,
  ) => Promise<ResearchWorkspace | null>;
  captureNoteRequest?: typeof researchBridge.captureResearchNote;
}

const buildSourceRef = (draft: ResearchComposerState): SourceReferenceInput | undefined => {
  if (!draft.sourceUrl && !draft.sourceTitle) {
    return undefined;
  }

  return {
    kind: draft.sourceKind,
    title: draft.sourceTitle || undefined,
    url: draft.sourceUrl || undefined,
  };
};

export const createResearchCaptureController = ({
  ensureWorkspace,
  captureNoteRequest = researchBridge.captureResearchNote,
}: ResearchCaptureControllerDependencies) => {
  return async ({
    draft,
    fallbackTicker,
    explicitWorkspaceId,
    autoCreateFromTicker = false,
  }: CaptureNoteArgs): Promise<NoteCaptureResult> => {
    const normalizedText = draft.rawText.trim();
    if (!normalizedText) {
      throw new Error('Note text is required.');
    }

    const resolvedTicker = draft.ticker.trim() || fallbackTicker?.trim() || undefined;
    const directWorkspaceId = explicitWorkspaceId || draft.workspaceId || undefined;
    const resolvedWorkspace = await ensureWorkspace({
      workspaceId: directWorkspaceId,
      ticker: autoCreateFromTicker ? resolvedTicker : undefined,
    });

    if (!resolvedWorkspace) {
      throw new Error('Select or create a research workspace before saving this note.');
    }

    return captureNoteRequest({
      workspaceId: resolvedWorkspace.id,
      rawText: normalizedText,
      ticker: resolvedTicker,
      userNoteTypeOverride: draft.userNoteTypeOverride,
      sourceRef: buildSourceRef(draft),
    });
  };
};

export const useResearchCaptureFlow = (
  dependencies: ResearchCaptureControllerDependencies,
) => {
  const captureNote = useCallback(
    createResearchCaptureController(dependencies),
    [dependencies],
  );

  return {
    captureNote,
  };
};
