import { useQuery } from '@tanstack/react-query';
import { api } from '../lib/api';
import type { ApiResponse } from '../lib/api';
import { useAuthStore } from '../stores/authStore';
import type { MySubscriptionData } from '../types';

export function useSubscription() {
  const primaryRole = useAuthStore((s) => s.primaryRole);
  const enabled = primaryRole === 'doctor' || primaryRole === 'clinic' || primaryRole === 'secretary';

  const { data } = useQuery<ApiResponse<MySubscriptionData>>({
    queryKey: ['subscription-my'],
    queryFn: () => api.get('/api/v1/subscription/my'),
    enabled,
    staleTime: 2 * 60 * 1000,
  });

  const sub = data?.data?.subscription ?? null;
  const effectivePlan = data?.data?.effective_plan ?? sub?.plan ?? null;
  const features: Record<string, boolean> = effectivePlan?.features ?? {};
  const maxSecretaries: number = effectivePlan?.max_secretaries ?? 1;
  const hasPlan = sub !== null;

  return {
    subscription: sub,
    hasFeature: (key: string) => features[key] ?? false,
    maxSecretaries,
    hasPlan,
    isExpiringSoon: (sub?.days_remaining ?? 0) > 0 && (sub?.days_remaining ?? 0) <= 7,
  };
}
