using Application.Abstractions.Data;
using Application.Abstractions.Cache;
using Application.Abstractions.Messaging;
using Application.Helpers;
using Domain.Entities.Members.Logs;
using SharedKernel.Results;
using Microsoft.EntityFrameworkCore;

namespace Application.Features.Api.MyPage.ChangeSummary;

internal sealed class Handler(
    IAppDbContext db,
    ICacheService cache
) : ICommandHandler<Command, Result>
{
    public async Task<Result> Handle(Command request, CancellationToken ct)
    {
        var summary = request.Summary?.Trim();

        if (string.IsNullOrWhiteSpace(summary))
        {
            return Result.Failure(Error.Problem("MyPage.SummaryRequired", "한마디는 필수입니다."));
        }

        if (summary.Length > 50)
        {
            return Result.Failure(Error.Problem("MyPage.SummaryTooLong", "한마디는 50자 이하여야 합니다."));
        }

        var member = await db.Member.FirstOrDefaultAsync(m => m.ID == request.MemberID, ct);
        if (member is null)
        {
            return Result.Failure(Error.NotFound("MyPage.MemberNotFound", "회원 정보를 찾을 수 없습니다."));
        }

        // 한마디 변경 주기 확인
        var accountConfig = await AccountConfigLoader.GetAccountConfigAsync(cache, db, ct);
        if (accountConfig.ChangeSummaryDay is > 0 && member.LastSummaryChangedAt.HasValue)
        {
            var nextChangeDate = member.LastSummaryChangedAt.Value.AddDays(accountConfig.ChangeSummaryDay.Value);
            if (DateTime.UtcNow < nextChangeDate)
            {
                return Result.Failure(Error.Problem("MyPage.SummaryChangeTooSoon",
                    $"한마디는 {accountConfig.ChangeSummaryDay}일마다 변경 가능합니다."));
            }
        }

        var log = MemberSummaryChangeLog.Create(request.MemberID, member.Summary, summary);
        await db.MemberSummaryChangeLog.AddAsync(log, ct);

        member.SetSummary(summary);

        await db.SaveChangesAsync(ct);

        return Result.Success();
    }
}
