import React from 'react';
import { getTenantPackagesOverview, getPackages, Package, TenantPackageSummary } from '../../api';

export type TenantPackagesState =
  | { status: 'loading' }
  | { status: 'error'; message: string }
  | {
      status: 'success';
      catalog: Package[];
      activePackage: TenantPackageSummary | null;
      purchasedPackages: TenantPackageSummary[];
    };

export function useTenantPackages(): TenantPackagesState {
  const [state, setState] = React.useState<TenantPackagesState>({ status: 'loading' });

  React.useEffect(() => {
    let cancelled = false;
    (async () => {
      try {
        const [tenantPackages, catalog] = await Promise.all([
          getTenantPackagesOverview(),
          getPackages('endcustomer'),
        ]);
        if (cancelled) return;
        setState({
          status: 'success',
          catalog,
          activePackage: tenantPackages.activePackage,
          purchasedPackages: tenantPackages.packages,
        });
      } catch (error) {
        console.error('[useTenantPackages] Failed to fetch', error);
        if (cancelled) return;
        setState({
          status: 'error',
          message: 'Pakete konnten nicht geladen werden. Bitte später erneut versuchen.',
        });
      }
    })();

    return () => {
      cancelled = true;
    };
  }, []);

  return state;
}
