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

import { apiClient } from "@/lib/api-client"

export interface SubscriptionData {
  planTier: string
  status: string
  memberLimit: number
  trialEndsAt: string | null
  currentPeriodStart: string | null
  currentPeriodEnd: string | null
  canceledAt: string | null
  hasStripeSubscription: boolean
}

export function useSubscriptionQuery() {
  return useQuery({
    queryKey: ["billing", "subscription"],
    queryFn: () => apiClient<SubscriptionData>("/billing/subscription"),
  })
}

export function useCreateCheckoutMutation() {
  return useMutation({
    mutationFn: async (planTier: string) => {
      const data = await apiClient<{ url: string }>("/billing/checkout", {
        method: "POST",
        body: { planTier },
      })
      return data
    },
    onSuccess: (data) => {
      window.location.href = data.url
    },
  })
}

export function useCreatePortalMutation() {
  return useMutation({
    mutationFn: async () => {
      const data = await apiClient<{ url: string }>("/billing/portal", {
        method: "POST",
      })
      return data
    },
    onSuccess: (data) => {
      window.location.href = data.url
    },
  })
}
