import "server-only";

import {
  assertManagedMemberCreationAllowedByOwnerEmail,
  createManagedMemberByOwnerEmail,
  deleteManagedMemberByOwnerEmail,
  getManagedMembersByOwnerEmail,
} from "@/lib/mail-automation";
import { hasOperationalBenefitByOwnerEmail } from "@/lib/mail-operational-benefit";
import {
  getPolarBillingOverviewByOwnerEmail,
  hasActivePolarGrowthPlanByOwnerEmail,
  syncActivePolarSubscriptionSeatsByOwnerEmail,
} from "@/lib/polar-billing";
import {
  requestManagedMemberSeatChargeByOwnerEmail,
  refundTossPayChargeById,
} from "@/lib/toss-pay";

type CreateManagedMemberInput = {
  displayName: string;
  localPart: string;
  password: string;
};

export async function createManagedMemberWithImmediateChargeByOwnerEmail(
  ownerEmail: string,
  input: CreateManagedMemberInput,
) {
  await assertManagedMemberCreationAllowedByOwnerEmail(ownerEmail, input);

  if (await hasOperationalBenefitByOwnerEmail(ownerEmail)) {
    await createManagedMemberByOwnerEmail(ownerEmail, input);

    return {
      status: "complimentary" as const,
    };
  }

  if (await hasActivePolarGrowthPlanByOwnerEmail(ownerEmail)) {
    const overview = await getPolarBillingOverviewByOwnerEmail(ownerEmail, {
      amount: 599,
      currency: "usd",
    });
    const previousSeatCount = overview?.billingSeatCount ?? 1;

    await syncActivePolarSubscriptionSeatsByOwnerEmail(ownerEmail, previousSeatCount + 1);

    try {
      await createManagedMemberByOwnerEmail(ownerEmail, input);
    } catch (error) {
      await syncActivePolarSubscriptionSeatsByOwnerEmail(ownerEmail, previousSeatCount).catch(
        () => undefined,
      );
      throw error;
    }

    return {
      provider: "polar" as const,
      seats: previousSeatCount + 1,
      status: "success" as const,
    };
  }

  const charge = await requestManagedMemberSeatChargeByOwnerEmail({
    displayName: input.displayName,
    email: ownerEmail,
    localPart: input.localPart,
  });

  if (charge.status !== "success") {
    throw new Error("member-charge-failed");
  }

  try {
    await createManagedMemberByOwnerEmail(ownerEmail, input);
  } catch {
    try {
      await refundTossPayChargeById({
        chargeId: charge.chargeId,
        reason: "멤버 추가 실패 자동 환불",
        requestedByEmail: ownerEmail,
      });
    } catch {
      throw new Error("member-charge-refund-failed");
    }

    throw new Error("member-create-refunded");
  }

  return charge;
}

export async function deleteManagedMemberWithBillingByOwnerEmail(
  ownerEmail: string,
  memberId: number,
) {
  const members = await getManagedMembersByOwnerEmail(ownerEmail);
  const member = members.find((item) => item.id === memberId);

  if (!member) {
    throw new Error("member-not-found");
  }

  const polarActive = await hasActivePolarGrowthPlanByOwnerEmail(ownerEmail);
  const previousSeatCount = members.length + 1;

  if (polarActive) {
    await syncActivePolarSubscriptionSeatsByOwnerEmail(
      ownerEmail,
      Math.max(1, previousSeatCount - 1),
    );
  }

  try {
    await deleteManagedMemberByOwnerEmail(ownerEmail, memberId);
  } catch (error) {
    if (polarActive) {
      await syncActivePolarSubscriptionSeatsByOwnerEmail(
        ownerEmail,
        previousSeatCount,
      ).catch(() => undefined);
    }
    throw error;
  }
}
