/**
 * Seed RevenueCat subscription plans (idempotent by revenueCatProductId).
 *
 * Products: premium_monthly, premium_yearly, family_monthly, family_yearly
 * Entitlements: premium, family (offering: default)
 *
 * Usage: npm run seed:revenuecat-plans
 */
import path from "path";
import dotenv from "dotenv";

dotenv.config({ path: path.join(__dirname, "..", "config", ".env") });

import mongoose from "mongoose";
import SubscriptionPlanModel from "../models/SubscriptionPlanModel";

type PlanSeed = {
  subscriptionName: string;
  subscriptionType: string;
  tier: string;
  monthlyPrice: number;
  yearlyPrice: number;
  revenueCatProductId: string;
  revenueCatEntitlement: "premium" | "family";
  slug: string;
  name: string;
  interval: "month" | "year";
  priceCents: number;
};

const PLANS: PlanSeed[] = [
  {
    subscriptionName: "premium_monthly",
    subscriptionType: "Monthly",
    tier: "Premium",
    monthlyPrice: 3.99,
    yearlyPrice: 45,
    revenueCatProductId: "premium_monthly",
    revenueCatEntitlement: "premium",
    slug: "premium-monthly",
    name: "Premium Monthly",
    interval: "month",
    priceCents: 399,
  },
  {
    subscriptionName: "premium_yearly",
    subscriptionType: "Yearly",
    tier: "Premium",
    monthlyPrice: 3.99,
    yearlyPrice: 45,
    revenueCatProductId: "premium_yearly",
    revenueCatEntitlement: "premium",
    slug: "premium-yearly",
    name: "Premium Yearly",
    interval: "year",
    priceCents: 4500,
  },
  {
    subscriptionName: "family_monthly",
    subscriptionType: "Monthly",
    tier: "Family",
    monthlyPrice: 7.99,
    yearlyPrice: 90,
    revenueCatProductId: "family_monthly",
    revenueCatEntitlement: "family",
    slug: "family-monthly",
    name: "Family Monthly",
    interval: "month",
    priceCents: 799,
  },
  {
    subscriptionName: "family_yearly",
    subscriptionType: "Yearly",
    tier: "Family",
    monthlyPrice: 7.99,
    yearlyPrice: 90,
    revenueCatProductId: "family_yearly",
    revenueCatEntitlement: "family",
    slug: "family-yearly",
    name: "Family Yearly",
    interval: "year",
    priceCents: 9000,
  },
];

async function main() {
  const dbUri = process.env.DB_URI;
  if (!dbUri) {
    console.error("DB_URI is missing in src/config/.env");
    process.exit(1);
  }

  await mongoose.connect(dbUri);
  console.log("Connected to MongoDB\nCreating subscription plans...\n");

  for (const plan of PLANS) {
    const doc = {
      subscriptionName: plan.subscriptionName,
      subscriptionType: plan.subscriptionType,
      tier: plan.tier,
      monthlyPrice: plan.monthlyPrice,
      yearlyPrice: plan.yearlyPrice,
      device: null as null,
      revenueCatProductId: plan.revenueCatProductId,
      revenueCatEntitlement: plan.revenueCatEntitlement,
      isActive: true,
      name: plan.name,
      slug: plan.slug,
      description: `RevenueCat ${plan.revenueCatEntitlement} / ${plan.revenueCatProductId}`,
      priceCents: plan.priceCents,
      currency: "USD",
      interval: plan.interval,
      features: [`entitlement:${plan.revenueCatEntitlement}`],
    };

    const existing = await SubscriptionPlanModel.findOne({
      revenueCatProductId: plan.revenueCatProductId,
    });

    if (existing) {
      await SubscriptionPlanModel.updateOne(
        { revenueCatProductId: plan.revenueCatProductId },
        { $set: doc },
      );
      console.log(`Updated ${plan.revenueCatProductId} — ${plan.tier} ${plan.subscriptionType}`);
    } else {
      await SubscriptionPlanModel.create(doc);
      console.log(`Created ${plan.revenueCatProductId} — ${plan.tier} ${plan.subscriptionType}`);
    }
  }

  const count = await SubscriptionPlanModel.countDocuments();
  console.log(`\nTotal subscription plans in database: ${count}`);
  await mongoose.disconnect();
  console.log("\nDisconnected from MongoDB");
}

main().catch(async (err) => {
  console.error("Error creating subscription plans:", err);
  await mongoose.disconnect().catch(() => undefined);
  process.exit(1);
});
