import { Document, Model, Schema, Types, model } from "mongoose";
import type {
  SubscriptionEntitlement,
  SubscriptionStatus,
} from "../constants/subscription";

export interface IRevenueCatSubscriptionEvent extends Document {
  revenueCatEventId: string;
  userId: Types.ObjectId;
  appUserId: string;
  eventType: string;
  productId?: string | null;
  entitlementIds: string[];
  activeEntitlement?: SubscriptionEntitlement | null;
  subscriptionStatus: SubscriptionStatus;
  purchasedAt?: Date | null;
  expirationAt?: Date | null;
  store?: string | null;
  environment?: string | null;
  /** From RevenueCat webhook `price` (USD or store currency). */
  priceCents?: number | null;
  currency?: string | null;
  processedAt: Date;
}

const RevenueCatSubscriptionEventSchema = new Schema<IRevenueCatSubscriptionEvent>(
  {
    revenueCatEventId: { type: String, required: true, unique: true, trim: true },
    userId: { type: Schema.Types.ObjectId, ref: "User", required: true },
    appUserId: { type: String, required: true, trim: true },
    eventType: { type: String, required: true, trim: true },
    productId: { type: String, trim: true, default: null },
    entitlementIds: { type: [String], default: [] },
    activeEntitlement: { type: String, default: null },
    subscriptionStatus: { type: String, required: true },
    purchasedAt: { type: Date, default: null },
    expirationAt: { type: Date, default: null },
    store: { type: String, trim: true, default: null },
    environment: { type: String, trim: true, default: null },
    priceCents: { type: Number, min: 0, default: null },
    currency: { type: String, trim: true, lowercase: true, default: null },
    processedAt: { type: Date, default: () => new Date() },
  },
  { timestamps: true },
);

RevenueCatSubscriptionEventSchema.index({ userId: 1, purchasedAt: -1, processedAt: -1 });
RevenueCatSubscriptionEventSchema.index({ userId: 1, productId: 1, purchasedAt: -1, priceCents: -1 });
RevenueCatSubscriptionEventSchema.index({ appUserId: 1, processedAt: -1 });
RevenueCatSubscriptionEventSchema.index({ eventType: 1, processedAt: -1 });

const RevenueCatSubscriptionEventModel: Model<IRevenueCatSubscriptionEvent> =
  model<IRevenueCatSubscriptionEvent>(
    "RevenueCatSubscriptionEvent",
    RevenueCatSubscriptionEventSchema,
  );

export default RevenueCatSubscriptionEventModel;
