import { useMutation } from "@tanstack/react-query";
import { useRouter } from "next/navigation";
import { useSession } from "next-auth/react";

interface OnboardData {
  firstName: string;
  lastName: string;
  userType: string;
  propertyCount?: string;
  goals: string[];
  referralSource: string;
  nrlaMembershipId?: string;
  marketingOptIn?: boolean;
}

export function useOnboardUser() {
  const router = useRouter();
  const { update } = useSession();

  return useMutation({
    mutationFn: async (data: OnboardData) => {
      // 1️) Create user profile
      const res1 = await fetch("/api/user/profile", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(data),
      });
      if (!res1.ok) throw new Error("Failed to create user profile");

      // 2️) Mark user as onboarded
      const res2 = await fetch("/api/user/onboarded", {
        method: "PATCH",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ onboarded: true }),
      });
      if (!res2.ok) throw new Error("Failed to update onboarding status");
    },
    onSuccess: async () => {
      // 3️) Redirect once both requests succeed
      // Refresh the token with the next-auth session update
      await update();
      router.push("/home");
    },
  });
}
