import { Injectable, BadRequestException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { MoreThan, Repository } from 'typeorm';
import { Material } from './material.entity';
import { CharacterMaterial } from './character-material.entity';
import { Character } from '../character/entities/character.entity';
import { User } from '../user/user.entity';

@Injectable()
export class MaterialService {
  constructor(
    @InjectRepository(Material)
    private readonly materialRepository: Repository<Material>,
    @InjectRepository(CharacterMaterial)
    private readonly charMatRepository: Repository<CharacterMaterial>,
    @InjectRepository(Character)
    private readonly characterRepository: Repository<Character>,
  ) {}

  findAll() {
    return this.materialRepository.find({ order: { rarity: 'ASC', name: 'ASC' } });
  }

  async getInventory(user: User) {
    const char = await this.getCharacter(user);
    return this.charMatRepository.find({
      where: { characterId: char.id, quantity: MoreThan(0) },
    });
  }

  // Appelé par CombatService après victoire (loot)
  async addMaterial(characterId: string, materialId: string, quantity: number): Promise<CharacterMaterial> {
    let entry = await this.charMatRepository.findOne({ where: { characterId, materialId } });
    if (entry) {
      entry.quantity += quantity;
    } else {
      entry = this.charMatRepository.create({ characterId, materialId, quantity });
    }
    return this.charMatRepository.save(entry);
  }

  // Appelé par CraftService pour consommer les ingrédients
  async consumeMaterials(characterId: string, ingredients: { materialId: string; quantity: number }[]): Promise<void> {
    for (const ing of ingredients) {
      const entry = await this.charMatRepository.findOne({
        where: { characterId, materialId: ing.materialId },
      });
      if (!entry || entry.quantity < ing.quantity) {
        throw new BadRequestException('Matériaux insuffisants pour ce craft');
      }
      entry.quantity -= ing.quantity;
      await this.charMatRepository.save(entry);
    }
  }

  private async getCharacter(user: User): Promise<Character> {
    const char = await this.characterRepository.findOne({ where: { userId: user.id } });
    if (!char) throw new BadRequestException('Aucun personnage trouvé');
    return char;
  }
}
