pet-companion-back/Services/SkillService.cs

85 lines
2.7 KiB
C#

using PetCompanion.Models;
using PetCompanion.Data;
using Microsoft.EntityFrameworkCore;
using PetCompanion.Repositories;
namespace PetCompanion.Services
{
public class SkillService
{
private readonly ApplicationDbContext _context;
private readonly PetRepository _petRepository;
private readonly PetSkillRepository _petSkillRepository;
public SkillService(
ApplicationDbContext context,
PetRepository petRepository,
PetSkillRepository petSkillRepository)
{
_context = context;
_petRepository = petRepository;
_petSkillRepository = petSkillRepository;
}
public PetSkill AllocateSkillPoint(string petId, string userId, int skillId)
{
var pet = _context.Pets
.Include(p => p.Skills)
.FirstOrDefault(p => p.Id == petId && p.UserId == userId);
if (pet == null)
throw new Exception("Pet not found");
if (pet.SkillPoints <= 0)
throw new Exception("No skill points available");
var skill = _context.Skills
.Include(s => s.Effects)
.FirstOrDefault(s => s.Id == skillId);
if (skill == null)
throw new Exception("Skill not found");
var existingSkill = pet.Skills.FirstOrDefault(ps => ps.SkillId == skillId);
if (existingSkill != null)
{
if (existingSkill.CurrentTier == SkillTier.III)
throw new Exception("Skill already at maximum tier");
existingSkill.CurrentTier++;
var effect = skill.Effects.FirstOrDefault(e => e.Tier == existingSkill.CurrentTier);
if (effect != null)
effect.PetSkillUpgrade(ref pet);
_petSkillRepository.SavePetSkill(existingSkill);
}
else
{
var newSkill = new PetSkill
{
PetId = petId,
SkillId = skillId,
CurrentTier = SkillTier.I
};
_petSkillRepository.SavePetSkill(newSkill);
var effect = skill.Effects.FirstOrDefault(e => e.Tier == SkillTier.I);
if (effect != null)
effect.PetSkillUpgrade(ref pet);
}
pet.SkillPoints--;
_context.SaveChanges();
return _petSkillRepository.GetPetSkills(petId).First(ps => ps.SkillId == skillId);
}
public IEnumerable<Skill> GetAvailableSkills()
{
return _context.Skills
.Include(s => s.Effects)
.ToList();
}
}
}