import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";

import { api } from "../client";
import type { components } from "../schema";
import { keys } from "../query-keys";

type UserView = components["schemas"]["UserView"];
type LoginRequest = components["schemas"]["LoginRequest"];

export function useMe() {
  return useQuery({
    queryKey: keys.me(),
    queryFn: async (): Promise<UserView | null> => {
      const { data, response } = await api.GET("/api/admin/me");

      if (response.status === 401) return null;

      if (!data) throw new Error("failed to load session");

      return data;
    },
    retry: false,
  });
}

export function useLogin() {
  const qc = useQueryClient();

  return useMutation({
    mutationFn: async (body: LoginRequest) => {
      const { response } = await api.POST("/api/admin/login", { body });

      if (response.status !== 204) {
        throw new Error(response.status === 401 ? "invalid" : "network");
      }
    },
    onSuccess: () => qc.invalidateQueries({ queryKey: keys.me() }),
    meta: { suppressErrorToast: true },
  });
}

export function useLogout() {
  const qc = useQueryClient();

  return useMutation({
    mutationFn: async () => {
      await api.POST("/api/admin/logout");
    },
    onSuccess: () => qc.setQueryData(keys.me(), null),
  });
}
