import { HttpException, HttpStatus, Injectable } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { GameTypeDocument, GameType } from '@schemas/game-type.schema';
import { UserDocument } from '@schemas/user.schema';
import { Model } from 'mongoose';

@Injectable()
export class GameTypesService {
  constructor(
    @InjectModel('gametypes') private gameTypeModel: Model<GameTypeDocument>,
    @InjectModel('users') private userModel: Model<UserDocument>,
  ) {}

  async create(data: Partial<GameType>, userId: string): Promise<GameType> {
    const user = await this.userModel.findById(userId).exec();
    if (!user) {
      throw new HttpException('Datos incorrectos', HttpStatus.BAD_REQUEST);
    }

    const gameType = new this.gameTypeModel(data);
    return gameType.save();
  }

  async findAll(userId: string): Promise<GameType[]> {
    const user = await this.userModel.findById(userId).exec();
    if (!user) {
      throw new HttpException('Datos incorrectos', HttpStatus.BAD_REQUEST);
    }

    return this.gameTypeModel.find({ businessId: user.businessId });
  }

  async findOne(id: string): Promise<GameType> {
    const gameType = await this.gameTypeModel.findById(id);
    if (!gameType)
      throw new HttpException('Juego no encontrado', HttpStatus.NOT_FOUND);
    return gameType;
  }

  async update(id: string, data: Partial<GameType>): Promise<GameType> {
    const updated = await this.gameTypeModel.findByIdAndUpdate(id, data, {
      new: true,
    });
    if (!updated)
      throw new HttpException('Juego no encontrado', HttpStatus.NOT_FOUND);
    return updated;
  }

  async delete(id: string): Promise<void> {
    const result = await this.gameTypeModel.findByIdAndDelete(id);
    if (!result)
      throw new HttpException('Juego no encontrado', HttpStatus.NOT_FOUND);
  }
}
