import { renderHook } from '@testing-library/react';
import { afterEach, describe, expect, it } from 'vitest';
import { getDataviewMenuRegistry } from '@ablogcms/plugins/core';
import type { AcmsContext } from '@ablogcms/url/types';
import useModuleAdminMenus, { type GetMenusContext } from './use-module-admin-menus';

const createContext = (): GetMenusContext => ({
  context: {} as AcmsContext,
  searchParams: new URLSearchParams(),
});

describe('useModuleAdminMenus', () => {
  it('ハンドラ0件でもコア定義のメニューがそのまま getMenus に渡る（特徴付けテスト）', () => {
    let received: string[] | undefined;
    renderHook(() =>
      useModuleAdminMenus({
        getMenus: (menus) => {
          received = menus.map((m) => m.id);
          return menus;
        },
        context: createContext(),
      })
    );

    expect(received).toEqual(['create', 'import']);
  });

  describe('ctx.dataview.registerMenu("module", ...) レジストリとのマージ', () => {
    afterEach(() => {
      getDataviewMenuRegistry().remove('module', 'plugin-menu');
    });

    it('レジストリに登録したメニューがコア定義の後ろに追加され getMenus に渡る', () => {
      getDataviewMenuRegistry().add('module', 'plugin-menu', { id: 'plugin-menu', label: 'プラグインメニュー' });

      const { result } = renderHook(() =>
        useModuleAdminMenus({ getMenus: (menus) => menus, context: createContext() })
      );

      expect(result.current.map((m) => m.id)).toEqual(['create', 'import', 'plugin-menu']);
    });

    it('レジストリ登録後もレガシー getMenus（フィルタ）が最終結果に適用される', () => {
      getDataviewMenuRegistry().add('module', 'plugin-menu', { id: 'plugin-menu', label: 'プラグインメニュー' });

      const { result } = renderHook(() =>
        useModuleAdminMenus({
          getMenus: (menus) => menus.filter((m) => m.id !== 'plugin-menu'),
          context: createContext(),
        })
      );

      expect(result.current.map((m) => m.id)).not.toContain('plugin-menu');
    });
  });
});
