import "server-only";

import { hasOperationalBenefitByOwnerEmail } from "@/lib/mail-operational-benefit";
import { hasActivePolarGrowthPlanByOwnerEmail } from "@/lib/polar-billing";
import {
  getMailBillingOwnershipByEmail,
  getMailBillingOverviewByOwnerEmail,
} from "@/lib/toss-pay";

export async function hasActiveGrowthPlanByOwnerEmail(email: string) {
  const ownership = await getMailBillingOwnershipByEmail(email);

  if (await hasOperationalBenefitByOwnerEmail(ownership.ownerEmail)) {
    return true;
  }

  const [tossOverview, polarActive] = await Promise.all([
    getMailBillingOverviewByOwnerEmail(ownership.ownerEmail, {
      recoverRemoteStatus: false,
    }).catch(() => null),
    hasActivePolarGrowthPlanByOwnerEmail(ownership.ownerEmail).catch(() => false),
  ]);
  const tossSubscription = tossOverview?.subscription;

  return (
    polarActive ||
    (tossSubscription?.status === "active" && tossSubscription.initialPaymentComplete)
  );
}
