import type { ModuleId } from '../types/moduleIds';
import type { AsukaModuleDefinition } from './modules';

export const NO_VIEW_MODULE_TITLE_KEY = 'ui.noViewModuleTitle';
export const NO_VIEW_MODULE_MESSAGE_KEY = 'ui.noViewModuleMessage';
export const NO_VIEW_MODULE_TOOLTIP_KEY = 'ui.noViewModuleTooltip';

const VIEW_INDEPENDENT_MODULE_IDS = new Set<ModuleId>([
  'views',
  'state',
  'license',
  'modelOptimizer',
]);

export interface ViewAvailabilityState {
  views?: unknown[] | null;
  documentViews?: unknown[] | null;
  activeViewId?: string | null;
}

export function hasAvailableView(state: ViewAvailabilityState | null | undefined): boolean {
  if (!state) return false;
  if (Array.isArray(state.views) && state.views.length > 0) return true;
  if (Array.isArray(state.documentViews) && state.documentViews.length > 0) return true;
  return false;
}

export function isViewIndependentModuleId(id: ModuleId | null | undefined): boolean {
  if (!id) return false;
  return VIEW_INDEPENDENT_MODULE_IDS.has(String(id));
}

export function doesModuleRequireView(module: Pick<AsukaModuleDefinition, 'id' | 'requiresView'> | ModuleId | null | undefined): boolean {
  if (!module) return true;

  if (typeof module === 'string') {
    return !isViewIndependentModuleId(module);
  }

  if (typeof module.requiresView === 'boolean') {
    return module.requiresView;
  }

  return !isViewIndependentModuleId(module.id);
}

export function isModuleBlockedWithoutView(
  module: Pick<AsukaModuleDefinition, 'id' | 'requiresView'> | ModuleId | null | undefined,
  hasView: boolean,
): boolean {
  return doesModuleRequireView(module) && !hasView;
}
