import type { SkillCapabilityMapping, SkillImportPreview } from './types';

export interface SkillImportConfirmState {
  categoryId?: number | string;
  conflictStrategy: 'OVERWRITE' | 'REJECT' | 'RENAME';
  renames?: Record<string, string>;
}

export function buildSkillImportConfirmPayload(
  preview: SkillImportPreview,
  state: SkillImportConfirmState,
  mappings: SkillCapabilityMapping[],
) {
  return {
    capabilityMappings: mappings.map((item) => ({
      bindingKey: item.bindingKey,
      disabled: item.disabled,
      targetId: item.disabled ? undefined : item.targetId,
    })),
    categoryId: state.categoryId || undefined,
    conflictStrategy: state.conflictStrategy,
    importToken: preview.importToken,
    renames: state.conflictStrategy === 'RENAME' ? state.renames : undefined,
  };
}

export function countBlockingImportIssues(preview?: SkillImportPreview) {
  if (!preview) return 0;
  return [
    ...(preview.issues || []),
    ...preview.skills.flatMap((item) => item.validationIssues || []),
  ].filter((issue) => issue.severity === 'ERROR').length;
}

export function invalidateConsumedImportPreview(
  preview: SkillImportPreview,
): SkillImportPreview {
  return { ...preview, importToken: '' };
}

export function resolveSkillImportConflictReasonLabel(reason?: string) {
  return reason === 'NOT_DRAFT' ? '当前状态不可覆盖' : '名称不可用';
}

export function resolveSkillImportStep(
  current: number,
  direction: 'next' | 'previous' | 'visible',
  hasCapabilityMappings: boolean,
) {
  if (direction === 'visible') {
    return hasCapabilityMappings || current < 2 ? current : 1;
  }
  if (direction === 'next') {
    return current === 0 && !hasCapabilityMappings
      ? 2
      : Math.min(current + 1, 2);
  }
  return current === 2 && !hasCapabilityMappings ? 0 : Math.max(current - 1, 0);
}
