using JSMR.Application.Creators.Commands.UpdateCreatorStatus;
using JSMR.Application.Creators.Contracts;
using JSMR.Application.Creators.Ports;
using JSMR.Domain.Entities;
using Microsoft.EntityFrameworkCore;

namespace JSMR.Infrastructure.Data.Repositories.Creators;

public class CreatorWriter(AppDbContext context) : ICreatorWriter
{
    public async Task<UpdateCreatorStatusResponse> UpdateStatusAsync(UpdateCreatorStatusRequest request, CancellationToken cancellationToken = default)
    {
        Creator creator = await GetCreatorAsync(request.CreatorId, cancellationToken);

        switch (request.CreatorStatus)
        {
            case CreatorStatus.Neutral:
                creator.Favorite = false;
                creator.Blacklisted = false;
                break;
            case CreatorStatus.Favorite:
                creator.Favorite = true;
                creator.Blacklisted = false;
                break;
            case CreatorStatus.Blacklisted:
                creator.Favorite = false;
                creator.Blacklisted = true;
                break;
        }

        await context.SaveChangesAsync(cancellationToken);

        return new UpdateCreatorStatusResponse(request.CreatorId, request.CreatorStatus);
    }

    private async Task<Creator> GetCreatorAsync(int creatorId, CancellationToken cancellationToken)
    {
        return await context.Creators.FirstOrDefaultAsync(creator => creator.CreatorId == creatorId, cancellationToken)
            ?? throw new KeyNotFoundException($"Creator {creatorId} not found.");
    }
}