using JSMR.Application.VoiceWorks.Commands.SetFavorite;
using JSMR.Application.VoiceWorks.Ports;
using JSMR.Domain.Entities;
using JSMR.Infrastructure.Common.Time;
using Microsoft.EntityFrameworkCore;

namespace JSMR.Infrastructure.Data.Repositories.VoiceWorks;

public class VoiceWorkWriter(AppDbContext dbContext) : IVoiceWorkWriter
{
    public async Task<SetVoiceWorkFavoriteResponse> SetFavoriteAsync(SetVoiceWorkFavoriteRequest request, CancellationToken cancellationToken)
    {
        VoiceWork voiceWork = await GetVoiceWorkAsync(request.VoiceWorkId, cancellationToken);
        voiceWork.Favorite = request.IsFavorite;

        await dbContext.SaveChangesAsync(cancellationToken);

        return new SetVoiceWorkFavoriteResponse(request.VoiceWorkId, request.IsFavorite);
    }

    private async Task<VoiceWork> GetVoiceWorkAsync(int voiceWorkId, CancellationToken cancellationToken)
    {
        return await dbContext.VoiceWorks.FirstOrDefaultAsync(voiceWork => voiceWork.VoiceWorkId == voiceWorkId, cancellationToken)
            ?? throw new KeyNotFoundException($"Voice Work {voiceWorkId} not found.");
    }
}