import { QUERY_KEYS } from "@/utils/query-key";
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import {
  getRoles,
  getRole,
  createRole,
  updateRole,
  deleteRole,
  getRolePermissions,
  assignPermissionToRole,
  removePermissionFromRole,
  getAllPermissions,
} from "./_requests";
import { CreateRoleRequest, UpdateRoleRequest, RoleFilters } from "./_models";
import { Role } from "@/types/auth";
import toast from "react-hot-toast";

export const useRoles = (filters?: RoleFilters) => {
  return useQuery({
    queryKey: [QUERY_KEYS.GET_ROLES, filters],
    queryFn: () => getRoles(filters),
  });
};

export const useRole = (id: string) => {
  return useQuery({
    queryKey: [QUERY_KEYS.GET_ROLE, id],
    queryFn: () => getRole(id),
    enabled: !!id,
  });
};

export const useCreateRole = () => {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: (roleData: CreateRoleRequest) => createRole(roleData),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: [QUERY_KEYS.GET_ROLES] });
      toast.success("نقش با موفقیت ایجاد شد");
    },
    onError: (error: any) => {
      toast.error(error?.message || "خطا در ایجاد نقش");
    },
  });
};

export const useUpdateRole = () => {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: (data: UpdateRoleRequest) =>
      updateRole(data.id.toString(), data),
    onSuccess: (data: Role) => {
      queryClient.invalidateQueries({ queryKey: [QUERY_KEYS.GET_ROLES] });
      queryClient.invalidateQueries({
        queryKey: [QUERY_KEYS.GET_ROLE, data.id.toString()],
      });
      toast.success("نقش با موفقیت به‌روزرسانی شد");
    },
    onError: (error: any) => {
      toast.error(error?.message || "خطا در به‌روزرسانی نقش");
    },
  });
};

export const useDeleteRole = () => {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: (id: string) => deleteRole(id),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: [QUERY_KEYS.GET_ROLES] });
      toast.success("نقش با موفقیت حذف شد");
    },
    onError: (error: any) => {
      toast.error(error?.message || "خطا در حذف نقش");
    },
  });
};

export const useRolePermissions = (id: string) => {
  return useQuery({
    queryKey: [QUERY_KEYS.GET_ROLE_PERMISSIONS, id],
    queryFn: () => getRolePermissions(id),
    enabled: !!id,
  });
};

export const useAssignPermission = () => {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: ({
      roleId,
      permissionId,
    }: {
      roleId: string;
      permissionId: string;
    }) => assignPermissionToRole(roleId, permissionId),
    onSuccess: (_, variables) => {
      queryClient.invalidateQueries({
        queryKey: [QUERY_KEYS.GET_ROLE_PERMISSIONS, variables.roleId],
      });
      queryClient.invalidateQueries({
        queryKey: [QUERY_KEYS.GET_ROLE, variables.roleId],
      });
      toast.success("دسترسی با موفقیت اختصاص داده شد");
    },
    onError: (error: any) => {
      toast.error(error?.message || "خطا در اختصاص دسترسی");
    },
  });
};

export const useRemovePermission = () => {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: ({
      roleId,
      permissionId,
    }: {
      roleId: string;
      permissionId: string;
    }) => removePermissionFromRole(roleId, permissionId),
    onSuccess: (_, variables) => {
      queryClient.invalidateQueries({
        queryKey: [QUERY_KEYS.GET_ROLE_PERMISSIONS, variables.roleId],
      });
      queryClient.invalidateQueries({
        queryKey: [QUERY_KEYS.GET_ROLE, variables.roleId],
      });
      toast.success("دسترسی با موفقیت حذف شد");
    },
    onError: (error: any) => {
      toast.error(error?.message || "خطا در حذف دسترسی");
    },
  });
};

export const usePermissions = () => {
  return useQuery({
    queryKey: [QUERY_KEYS.GET_PERMISSIONS],
    queryFn: () => getAllPermissions(),
  });
};
