import { Document, Model, Schema, model } from "mongoose";
import { SUBSCRIPTION_ENTITLEMENT } from "../constants/subscription";

export interface ISubscriptionPlan extends Document {
  name: string;
  slug: string;
  description: string;
  priceCents: number;
  currency: string;
  interval: "month" | "year" | "one_time";
  features: string[];
  isActive: boolean;
  /** RevenueCat / catalog fields */
  subscriptionName?: string;
  subscriptionType?: string;
  tier?: string;
  monthlyPrice?: number;
  yearlyPrice?: number;
  device?: "IOS" | "Android" | "ALL" | null;
  revenueCatProductId?: string;
  revenueCatEntitlement?: string;
}

const SubscriptionPlanSchema = new Schema<ISubscriptionPlan>(
  {
    name: { type: String, required: true, trim: true },
    slug: { type: String, required: true, unique: true, trim: true },
    description: { type: String, default: "" },
    priceCents: { type: Number, required: true, min: 0 },
    currency: { type: String, default: "usd", uppercase: true },
    interval: {
      type: String,
      enum: ["month", "year", "one_time"],
      required: true,
    },
    features: { type: [String], default: [] },
    isActive: { type: Boolean, default: true },
    subscriptionName: { type: String, trim: true },
    subscriptionType: { type: String, trim: true },
    tier: { type: String, trim: true },
    monthlyPrice: { type: Number, min: 0 },
    yearlyPrice: { type: Number, min: 0 },
    device: {
      type: String,
      enum: ["IOS", "Android", "ALL", null],
      default: null,
    },
    revenueCatProductId: { type: String, trim: true, sparse: true },
    revenueCatEntitlement: {
      type: String,
      enum: SUBSCRIPTION_ENTITLEMENT,
    },
  },
  { timestamps: true },
);

SubscriptionPlanSchema.index(
  { revenueCatProductId: 1 },
  { unique: true, sparse: true },
);

const SubscriptionPlanModel: Model<ISubscriptionPlan> = model<ISubscriptionPlan>(
  "SubscriptionPlan",
  SubscriptionPlanSchema,
);

export default SubscriptionPlanModel;
