import type { SkillInfo } from './types';

export interface SkillDraftPayload {
  categoryId?: number | string;
  displayName?: string;
  enabled?: boolean;
  id?: number | string;
  skillContent?: string;
  visibilityScope?: string;
}

export interface SkillBasicValidationErrors {
  description?: string;
  displayName?: string;
  name?: string;
}

const CANONICAL_SKILL_NAME = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;

/** Build the narrow DTO accepted by the Skill draft endpoints. */
export function buildSkillDraftPayload(
  skill: SkillInfo,
  includeId: boolean,
): SkillDraftPayload {
  const payload: SkillDraftPayload = {
    categoryId: skill.categoryId,
    displayName: skill.displayName,
    enabled: skill.enabled,
    visibilityScope: skill.visibilityScope,
  };
  if (includeId) payload.id = skill.id;
  else payload.skillContent = skill.skillContent;
  return payload;
}

/** Validate fields that are editable in the basic-information section. */
export function validateSkillBasic(
  skill: SkillInfo,
  isNew: boolean,
): SkillBasicValidationErrors {
  const errors: SkillBasicValidationErrors = {};
  const displayName = String(skill.displayName || '').trim();
  if (!displayName) {
    errors.displayName = '请输入显示名称';
  } else if (displayName.length > 128) {
    errors.displayName = '显示名称不能超过 128 个字符';
  }
  if (!isNew) return errors;

  const name = String(skill.name || '').trim();
  if (!name) {
    errors.name = '请输入标准名称';
  } else if (name.length > 64) {
    errors.name = '标准名称不能超过 64 个字符';
  } else if (!CANONICAL_SKILL_NAME.test(name)) {
    errors.name = '仅支持小写字母、数字和连字符';
  }
  const description = String(skill.description || '').trim();
  if (!description) {
    errors.description = '请输入标准描述';
  } else if (description.length > 1024) {
    errors.description = '标准描述不能超过 1024 个字符';
  }
  return errors;
}
