using Application.Abstractions.Messaging;
using Application.Abstractions.Data;
using Application.Abstractions.Cache;
using Domain.Entities.Common;
using Microsoft.EntityFrameworkCore;

namespace Application.Features.Admin.Crypto.TickerConfig.Save;

public sealed class Handler(IAppDbContext db, ICacheService cache) : ICommandHandler<Command>
{
    public async Task Handle(Command request, CancellationToken ct)
    {
        var config = await db.Config.OrderByDescending(x => x.ID).FirstOrDefaultAsync(ct);
        if (config is null)
        {
            config = Domain.Entities.Common.Config.Create();
            db.Config.Add(config);
        }

        var crypto = new CryptoConfig
        {
            TickerRefreshSeconds = request.TickerRefreshSeconds,
            SurgeThreshold = request.SurgeThreshold,
            PlungeThreshold = request.PlungeThreshold,
            MainPageCoinCount = request.MainPageCoinCount
        };

        config.Update(
            config.Basic,
            config.Images,
            config.Meta,
            config.Company,
            config.Account,
            config.EmailTemplate,
            config.External,
            config.Payment,
            crypto
        );

        await db.SaveChangesAsync(ct);
        await cache.RemoveAsync(CacheKeys.Config, ct);
    }
}