import "server-only";

import { ModulePlanPurchaseStatus, type ModulePlanKey, type Prisma, type PrismaClient } from "@prisma/client";

type PaymentSyncInput = {
  externalReference: string;
  paymentId: string;
  paymentStatus: string;
  mercadoOrderId?: string | null;
  rawPayload?: unknown;
};

export function isApprovedPaymentStatus(status: string) {
  return status.toLowerCase() === "approved";
}

function resolvePurchaseStatus(status: string) {
  const normalized = status.toLowerCase();

  if (normalized === "approved") {
    return ModulePlanPurchaseStatus.APPROVED;
  }

  if (normalized === "rejected") {
    return ModulePlanPurchaseStatus.REJECTED;
  }

  if (normalized === "cancelled") {
    return ModulePlanPurchaseStatus.CANCELLED;
  }

  return ModulePlanPurchaseStatus.PENDING;
}

function getPlanDurationDays() {
  const raw = process.env.MP_PLAN_DURATION_DAYS?.trim() || "30";
  const parsed = Number(raw);

  if (!Number.isFinite(parsed) || parsed <= 0) {
    return 30;
  }

  return Math.floor(parsed);
}

function computePlanExpiration(from: Date) {
  const expiration = new Date(from);
  expiration.setDate(expiration.getDate() + getPlanDurationDays());
  return expiration;
}

export async function syncPurchaseFromPayment(prisma: PrismaClient, input: PaymentSyncInput) {
  const purchase = await prisma.modulePlanPurchase.findUnique({
    where: { externalReference: input.externalReference },
    select: {
      id: true,
      userId: true,
      planKey: true,
      status: true,
    },
  });

  if (!purchase) {
    return null;
  }

  const resolvedStatus = resolvePurchaseStatus(input.paymentStatus);
  const now = new Date();

  await prisma.modulePlanPurchase.update({
    where: { id: purchase.id },
    data: {
      status: resolvedStatus,
      mercadoPaymentId: input.paymentId,
      mercadoOrderId: input.mercadoOrderId ?? undefined,
      approvedAt: resolvedStatus === ModulePlanPurchaseStatus.APPROVED ? now : undefined,
      responseJson: (input.rawPayload ?? {}) as Prisma.InputJsonValue,
    },
  });

  if (!isApprovedPaymentStatus(input.paymentStatus)) {
    return purchase;
  }

  await prisma.modulePlanSubscription.upsert({
    where: {
      userId_planKey: {
        userId: purchase.userId,
        planKey: purchase.planKey as ModulePlanKey,
      },
    },
    update: {
      sourcePurchaseId: purchase.id,
      isActive: true,
      startsAt: now,
      expiresAt: computePlanExpiration(now),
    },
    create: {
      userId: purchase.userId,
      planKey: purchase.planKey as ModulePlanKey,
      sourcePurchaseId: purchase.id,
      isActive: true,
      startsAt: now,
      expiresAt: computePlanExpiration(now),
    },
  });

  return purchase;
}
