import { useAuthStore } from '@/store/authStore'

export function useSubscription() {
  const subscription = useAuthStore((s) => s.subscription)

  const plan = subscription?.subscription.plan ?? 'free'
  const limits = subscription?.limits ?? null
  const usage = subscription?.usage ?? null
  const isActive = subscription?.subscription.status === 'active' || subscription?.subscription.status === 'trialing'

  const isPaidPlan = plan === 'pro' || plan === 'team'

  const canUseFeature = (feature: 'custom_branding' | 'priority_support'): boolean => {
    if (!limits) return false
    return limits[feature]
  }

  const isAtTreeLimit = (): boolean => {
    if (!limits || !usage) return false
    if (limits.max_trees === null) return false // unlimited
    return usage.tree_count >= limits.max_trees
  }

  const isAtSessionLimit = (): boolean => {
    if (!limits || !usage) return false
    if (limits.max_sessions_per_month === null) return false
    return usage.session_count_this_month >= limits.max_sessions_per_month
  }

  const formatLimit = (value: number | null): string => {
    return value === null ? 'Unlimited' : String(value)
  }

  return {
    plan,
    limits,
    usage,
    isActive,
    isPaidPlan,
    canUseFeature,
    isAtTreeLimit,
    isAtSessionLimit,
    formatLimit,
  }
}
