import { useMemo } from "react";
import type { Viewport } from "./types.js";

/**
 * useViewports - 视口列表查询
 *
 * 用途：按 scope 过滤当前用户的可用视口（iam 4 层视口模型）。
 * 视口数据由调用方注入（apps/* 从 iam /iam/viewports 获取后传入）。
 *
 * iam 视口 4 层：admin / teacher / student / parent
 *
 * @example
 * const { viewports, getByType, hasViewport } = useViewports({ viewports });
 * const teacherViewports = getByType("teacher");
 */

export interface UseViewportsProps {
  /** 当前用户的视口列表（从 iam 获取） */
  viewports: Viewport[] | null;
}

export interface UseViewportsReturn {
  /** 全部视口 */
  viewports: Viewport[];
  /** 按类型过滤 */
  getByType: (type: Viewport["type"]) => Viewport[];
  /** 检查是否拥有指定类型视口 */
  hasViewport: (type: Viewport["type"]) => boolean;
  /** 按 ID 查找 */
  getById: (id: string) => Viewport | undefined;
}

export function useViewports({
  viewports: input,
}: UseViewportsProps): UseViewportsReturn {
  const viewports = useMemo(() => input ?? [], [input]);

  const getByType = useMemo(
    () =>
      (type: Viewport["type"]): Viewport[] =>
        viewports.filter((v) => v.type === type),
    [viewports],
  );

  const hasViewport = useMemo(
    () =>
      (type: Viewport["type"]): boolean =>
        viewports.some((v) => v.type === type),
    [viewports],
  );

  const getById = useMemo(
    () =>
      (id: string): Viewport | undefined =>
        viewports.find((v) => v.id === id),
    [viewports],
  );

  return {
    viewports,
    getByType,
    hasViewport,
    getById,
  };
}
