/**
 * 视口配置 Hooks
 *
 * contract §2.4：adminViewports / updateViewport
 */
import { useCallback } from "react";
import { useGraphMutation, useGraphQuery } from "./use-graphql";
import {
  ADMIN_VIEWPORTS_QUERY,
  UPDATE_VIEWPORT_MUTATION,
} from "@/lib/graphql-client";
import type { ViewportConfigViewModel } from "@/types/view-models";

interface AdminViewportsResponse {
  adminViewports: ViewportConfigViewModel[];
}

interface UpdateViewportResponse {
  updateViewport: {
    id: string;
    key: string;
    label: string;
    sortOrder: number;
    isVisible: boolean;
  };
}

interface UpdateViewportInput {
  label?: string;
  sortOrder?: number;
  isVisible?: boolean;
  requiredPermission?: string | null;
}

export function useViewports(scope?: string) {
  const result = useGraphQuery<AdminViewportsResponse>(
    ADMIN_VIEWPORTS_QUERY,
    scope ? { scope } : undefined,
  );
  return {
    ...result,
    data: result.data?.adminViewports ?? [],
  };
}

export function useUpdateViewport() {
  const [run, state] = useGraphMutation<
    UpdateViewportResponse,
    { id: string; input: UpdateViewportInput }
  >(UPDATE_VIEWPORT_MUTATION);
  const update = useCallback(
    async (id: string, input: UpdateViewportInput) => {
      const res = await run({ id, input });
      return res.data?.updateViewport ?? null;
    },
    [run],
  );
  return [update, state] as const;
}
