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

export interface IAchievement {
  id: string;
  name: string;
  description: string;
  dateUnlocked: Date;
}

export interface IInventoryItem {
  itemId: mongoose.Types.ObjectId;
  name: string;
  description: string;
  quantity: number;
  imageUrl: string;
}

export interface IUser extends Document {
  telegramId: string;
  username: string;
  level: number;
  experience: number;
  balance: number;
  achievements: IAchievement[];
  inventory: IInventoryItem[];
  addAchievement: (achievement: IAchievement) => Promise<void>;
  createdAt: Date;
  updatedAt: Date;
}

const UserSchema: Schema = new Schema({
  telegramId: { type: String, required: true, unique: true },
  username: { type: String, required: true },
  level: { type: Number, default: 1 },
  experience: { type: Number, default: 0 },
  balance: { type: Number, default: 0 },
  achievements: [{
    id: String,
    name: String,
    description: String,
    dateUnlocked: { type: Date, default: Date.now }
  }],
  inventory: [{
    itemId: { type: Schema.Types.ObjectId, ref: 'ShopItem' },
    name: String,
    description: String,
    quantity: Number,
    imageUrl: String
  }]
}, {
  timestamps: true
});

// Метод для добавления опыта и повышения уровня
UserSchema.methods.addExperience = async function(amount: number) {
  this.experience += amount;
  
  // Простая формула для определения необходимого опыта для следующего уровня
  const expNeeded = this.level * 100;
  
  while (this.experience >= expNeeded) {
    this.experience -= expNeeded;
    this.level += 1;
    // Бонус за новый уровень
    this.balance += this.level * 10;
  }
  
  await this.save();
};

// Метод для добавления достижения
UserSchema.methods.addAchievement = async function(achievement: IAchievement) {
  if (!this.achievements.some(a => a.id === achievement.id)) {
    this.achievements.push(achievement);
    // Награда за достижение
    this.balance += 50;
    await this.save();
  }
};

export default mongoose.model<IUser>('User', UserSchema); 