import mongoose, { Document, Schema } from 'mongoose';

export type UserPlan = 'free' | 'basic' | 'premium' | 'max' | 'business';
export type BillingCycle = 'monthly' | 'yearly';
export type SubscriptionStatus = 'active' | 'canceled' | 'past_due' | 'paused' | 'trialing';

export interface IUser extends Document {
  email: string;
  passwordHash?: string;
  role: string;
  provider: 'local' | 'google' | 'apple';
  googleId?: string;
  appleId?: string;
  plan: UserPlan;
  planBillingCycle: BillingCycle;
  paddleCustomerId?: string;
  paddleSubscriptionId?: string;
  paddleTransactionId?: string;
  subscriptionStatus?: SubscriptionStatus;
  subscriptionCurrentPeriodEnd?: Date;
  subscriptionCanceledAt?: Date;
  createdAt: Date;
  updatedAt: Date;
}

const UserSchema = new Schema<IUser>(
  {
    email: { type: String, required: true, unique: true, lowercase: true, trim: true },
    passwordHash: { type: String },
    role: { type: String, required: true, default: 'user' },
    provider: { type: String, required: true, enum: ['local', 'google', 'apple'] },
    googleId: { type: String, sparse: true },
    appleId: { type: String, sparse: true },
    plan: { type: String, required: true, enum: ['free', 'basic', 'premium', 'max', 'business'], default: 'free' },
    planBillingCycle: { type: String, required: true, enum: ['monthly', 'yearly'], default: 'monthly' },
    paddleCustomerId: { type: String, sparse: true },
    paddleSubscriptionId: { type: String, sparse: true },
    paddleTransactionId: { type: String },
    subscriptionStatus: { type: String, enum: ['active', 'canceled', 'past_due', 'paused', 'trialing'] },
    subscriptionCurrentPeriodEnd: { type: Date },
    subscriptionCanceledAt: { type: Date },
  },
  { timestamps: true }
);

UserSchema.index({ googleId: 1 }, { sparse: true });
UserSchema.index({ appleId: 1 }, { sparse: true });
UserSchema.index({ paddleCustomerId: 1 }, { sparse: true });
UserSchema.index({ paddleSubscriptionId: 1 }, { sparse: true });

export const UserModel = mongoose.model<IUser>('User', UserSchema);
