using Microsoft.EntityFrameworkCore;
using UniVerse.Application.DTOs.Achievements;
using UniVerse.Application.Interfaces;
using UniVerse.Application.Mappings;
using UniVerse.Domain.Entities;
using UniVerse.Domain.Exceptions;
using UniVerse.Infrastructure.Data;

namespace UniVerse.Infrastructure.Services;

public class AchievementService : IAchievementService
{
    private readonly AppDbContext _db;
    public AchievementService(AppDbContext db) => _db = db;

    public async Task<List<AchievementDto>> GetAllAsync() =>
        await _db.Achievements.OrderBy(a => a.Id).Select(a => a.ToDto()).ToListAsync();

    public async Task<AchievementDto> GetByIdAsync(int id)
    {
        var a = await _db.Achievements.FindAsync(id) ?? throw new NotFoundException("Achievement", id);
        return a.ToDto();
    }

    public async Task<AchievementDto> CreateAsync(CreateAchievementRequest req)
    {
        var a = new Achievement
        {
            Name = req.Name, Description = req.Description, IconUrl = req.IconUrl,
            XpReward = req.XpReward, CoinReward = req.CoinReward, Condition = req.Condition
        };
        _db.Achievements.Add(a);
        await _db.SaveChangesAsync();
        return a.ToDto();
    }

    public async Task<AchievementDto> UpdateAsync(int id, UpdateAchievementRequest req)
    {
        var a = await _db.Achievements.FindAsync(id) ?? throw new NotFoundException("Achievement", id);
        a.Name = req.Name; a.Description = req.Description; a.IconUrl = req.IconUrl;
        a.XpReward = req.XpReward; a.CoinReward = req.CoinReward; a.Condition = req.Condition;
        await _db.SaveChangesAsync();
        return a.ToDto();
    }

    public async Task DeleteAsync(int id)
    {
        var a = await _db.Achievements.FindAsync(id) ?? throw new NotFoundException("Achievement", id);
        _db.Achievements.Remove(a);
        await _db.SaveChangesAsync();
    }
}
