/**
 * 角色权限 Hooks
 *
 * contract §2.4：adminRoles / createRole / updateRolePermissions
 */
import { useCallback } from "react";
import { useGraphMutation, useGraphQuery } from "./use-graphql";
import {
  ADMIN_ROLES_QUERY,
  CREATE_ROLE_MUTATION,
  UPDATE_ROLE_PERMISSIONS_MUTATION,
} from "@/lib/graphql-client";
import type { RoleViewModel } from "@/types/view-models";

interface AdminRolesResponse {
  adminRoles: RoleViewModel[];
}

interface CreateRoleResponse {
  createRole: { id: string; name: string; code: string };
}

interface UpdateRolePermissionsResponse {
  updateRolePermissions: {
    id: string;
    permissions: { id: string; code: string }[];
  };
}

interface CreateRoleInput {
  name: string;
  code: string;
  description?: string;
  dataScope?: string;
}

export function useRoles() {
  const result = useGraphQuery<AdminRolesResponse>(ADMIN_ROLES_QUERY);
  return {
    ...result,
    data: result.data?.adminRoles ?? [],
  };
}

export function useCreateRole() {
  const [run, state] = useGraphMutation<
    CreateRoleResponse,
    { input: CreateRoleInput }
  >(CREATE_ROLE_MUTATION);
  const create = useCallback(
    async (input: CreateRoleInput) => {
      const res = await run({ input });
      return res.data?.createRole ?? null;
    },
    [run],
  );
  return [create, state] as const;
}

export function useUpdateRolePermissions() {
  const [run, state] = useGraphMutation<
    UpdateRolePermissionsResponse,
    { roleId: string; permissionCodes: string[] }
  >(UPDATE_ROLE_PERMISSIONS_MUTATION);
  const update = useCallback(
    async (roleId: string, permissionCodes: string[]) => {
      const res = await run({ roleId, permissionCodes });
      return res.data?.updateRolePermissions ?? null;
    },
    [run],
  );
  return [update, state] as const;
}
