import type { AgentReference } from '@ftb/shared';

export interface DecomposeAdoptionRequirement {
  id: string;
  code: string;
  title: string;
}

export interface DecomposeDraftRequirementInput {
  requirementName?: string;
  references: AgentReference[];
}

export interface DecomposeDraftRequirementFields {
  requirementId: string;
  requirementName?: string;
}

export function resolveDecomposeDraftRequirementFields(
  draft: DecomposeDraftRequirementInput,
  requirements: DecomposeAdoptionRequirement[],
): DecomposeDraftRequirementFields {
  const reqRef = draft.references.find((ref) => ref.type === 'requirement');
  if (reqRef) {
    const requirement = requirements.find((item) => item.id === reqRef.id || item.code === reqRef.id);
    return {
      requirementId: requirement?.id ?? reqRef.id,
      requirementName: undefined,
    };
  }

  return {
    requirementId: '',
    requirementName: normalizePrototypeOnlyRequirementName(draft.requirementName, draft.references),
  };
}

function normalizePrototypeOnlyRequirementName(
  requirementName: string | undefined,
  references: AgentReference[],
): string {
  const trimmed = requirementName?.trim();
  if (trimmed) return trimmed;
  const note = references.find((ref) => ref.type === 'prototype_note');
  return note?.label?.trim() || note?.id?.trim() || '未命名需求';
}
