import { BillingInterval, SubscriptionStatus } from "@prisma/client";
import { db } from "@/lib/db";
import type { WooAccountInput } from "@/lib/auth/woo-sso";

export type WooEntitlementInput = WooAccountInput & {
  providerSubscriptionId: string;
  planCode: string;
  status: SubscriptionStatus;
  billingInterval: BillingInterval;
  currentPeriodEnd?: string | null;
  trialEndsAt?: string | null;
};

function nullableDate(value?: string | null) {
  if (!value) return null;
  const date = new Date(value);
  return Number.isNaN(date.getTime()) ? null : date;
}

export async function syncWooEntitlement(account: { organizationId: string }, entitlement: WooEntitlementInput) {
  const plan = await db.plan.findFirst({ where: { code: entitlement.planCode, isActive: true } });
  if (!plan) throw new Error("The WooCommerce subscription references an unknown AI Web Command plan.");

  return db.subscription.upsert({
    where: { organizationId: account.organizationId },
    update: {
      planId: plan.id,
      provider: "woocommerce",
      providerCustomerId: entitlement.customerId,
      providerSubscriptionId: entitlement.providerSubscriptionId,
      status: entitlement.status,
      billingInterval: entitlement.billingInterval,
      currentPeriodEnd: nullableDate(entitlement.currentPeriodEnd),
      trialEndsAt: nullableDate(entitlement.trialEndsAt),
    },
    create: {
      organizationId: account.organizationId,
      planId: plan.id,
      provider: "woocommerce",
      providerCustomerId: entitlement.customerId,
      providerSubscriptionId: entitlement.providerSubscriptionId,
      status: entitlement.status,
      billingInterval: entitlement.billingInterval,
      currentPeriodEnd: nullableDate(entitlement.currentPeriodEnd),
      trialEndsAt: nullableDate(entitlement.trialEndsAt),
    },
    include: { plan: true },
  });
}
