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

import { describe, expect, it } from 'vitest';

import {
  buildSkillCategoryPayload,
  canCreateSkillSubcategory,
  flattenSkillCategories,
  getSkillCategoryParentOptions,
} from './skill-category';

const categories: SkillCategory[] = [
  {
    categoryName: '研发',
    id: 1,
    levelNo: 1,
    children: [
      {
        categoryName: '平台',
        id: 2,
        levelNo: 2,
        parentId: 1,
        children: [
          {
            categoryName: '运行时',
            id: 3,
            levelNo: 3,
            parentId: 2,
          },
        ],
      },
    ],
  },
  { categoryName: '运营', id: 4, levelNo: 1 },
];

describe('skill category helpers', () => {
  it('flattens categories with stable display depth', () => {
    expect(
      flattenSkillCategories(categories).map(({ depth, id }) => ({
        depth,
        id,
      })),
    ).toEqual([
      { depth: 0, id: 1 },
      { depth: 1, id: 2 },
      { depth: 2, id: 3 },
      { depth: 0, id: 4 },
    ]);
  });

  it('only sends writable category fields', () => {
    expect(
      buildSkillCategoryPayload(
        {
          categoryName: '  产品  ',
          id: 9,
          parentId: '',
          sortNo: 3.8,
          status: 0,
        },
        true,
      ),
    ).toEqual({
      categoryName: '产品',
      id: 9,
      parentId: undefined,
      sortNo: 3,
      status: 0,
    });
  });

  it('prevents cycles and moves that would exceed three levels', () => {
    expect(
      getSkillCategoryParentOptions(categories, 1).map(({ id }) => id),
    ).toEqual([]);
    expect(
      getSkillCategoryParentOptions(categories, 2).map(({ id }) => id),
    ).toEqual([1, 4]);
    expect(
      getSkillCategoryParentOptions(categories).map(({ id }) => id),
    ).toEqual([1, 2, 4]);
  });

  it('allows adding children only below level three', () => {
    const flattened = flattenSkillCategories(categories);
    expect(flattened[1] && canCreateSkillSubcategory(flattened[1])).toBe(true);
    expect(flattened[2] && canCreateSkillSubcategory(flattened[2])).toBe(false);
  });
});
