using Application.Classes; using Application.DataTransferObjects.DesertStorm; using Application.Errors; using Application.Interfaces; using AutoMapper; using AutoMapper.QueryableExtensions; using Database; using Database.Entities; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Logging; namespace Application.Repositories; public class DesertStormRepository(ApplicationContext context, IMapper mapper, ILogger logger) : IDesertStormRepository { public async Task> GetDesertStormAsync(Guid desertStormId, CancellationToken cancellationToken) { var desertStormById = await context.DesertStorms .ProjectTo(mapper.ConfigurationProvider) .AsNoTracking() .FirstOrDefaultAsync(desertStorm => desertStorm.Id == desertStormId, cancellationToken); return desertStormById is null ? Result.Failure(DesertStormErrors.NotFound) : Result.Success(desertStormById); } public async Task>> GetPlayerDesertStormsAsync(Guid playerId, CancellationToken cancellationToken) { var playerDesertStorms = await context.DesertStorms .Where(desertStorm => desertStorm.PlayerId == playerId) .ProjectTo(mapper.ConfigurationProvider) .AsNoTracking() .ToListAsync(cancellationToken); return Result.Success(playerDesertStorms); } public async Task> CreateDesertStormAsync(CreateDesertStormDto createDesertStormDto, CancellationToken cancellationToken) { var newDesertStorm = mapper.Map(createDesertStormDto); await context.DesertStorms.AddAsync(newDesertStorm, cancellationToken); try { await context.SaveChangesAsync(cancellationToken); return Result.Success(mapper.Map(newDesertStorm)); } catch (Exception e) { logger.LogError(e, e.Message); return Result.Failure(GeneralErrors.DatabaseError); } } public async Task> UpdateDesertStormAsync(UpdateDesertStormDto updateDesertStormDto, CancellationToken cancellationToken) { var desertStormToUpdate = await context.DesertStorms .FirstOrDefaultAsync(desertStorm => desertStorm.Id == updateDesertStormDto.Id, cancellationToken); if (desertStormToUpdate is null) return Result.Failure(DesertStormErrors.NotFound); mapper.Map(updateDesertStormDto, desertStormToUpdate); try { await context.SaveChangesAsync(cancellationToken); return Result.Success(mapper.Map(desertStormToUpdate)); } catch (Exception e) { logger.LogError(e, e.Message); return Result.Failure(GeneralErrors.DatabaseError); } } public async Task> DeleteDesertStormAsync(Guid desertStormId, CancellationToken cancellationToken) { var desertStormToDelete = await context.DesertStorms .FirstOrDefaultAsync(desertStorm => desertStorm.Id == desertStormId, cancellationToken); if (desertStormToDelete is null) return Result.Failure(DesertStormErrors.NotFound); context.DesertStorms.Remove(desertStormToDelete); try { await context.SaveChangesAsync(cancellationToken); return Result.Success(true); } catch (Exception e) { logger.LogError(e, e.Message); return Result.Failure(GeneralErrors.DatabaseError); } } }