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.ChangeIntro;

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

        if (string.IsNullOrWhiteSpace(intro))
        {
            return Result.Failure(Error.Problem("MyPage.IntroRequired", "자기소개는 필수입니다."));
        }

        if (intro.Length > 3000)
        {
            return Result.Failure(Error.Problem("MyPage.IntroTooLong", "자기소개는 3000자 이하여야 합니다."));
        }

        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.ChangeIntroDay is > 0 && member.LastIntroChangedAt.HasValue)
        {
            var nextChangeDate = member.LastIntroChangedAt.Value.AddDays(accountConfig.ChangeIntroDay.Value);
            if (DateTime.UtcNow < nextChangeDate)
            {
                return Result.Failure(Error.Problem("MyPage.IntroChangeTooSoon",
                    $"자기소개는 {accountConfig.ChangeIntroDay}일마다 변경 가능합니다."));
            }
        }

        var log = MemberIntroChangeLog.Create(request.MemberID, member.Intro, intro);
        await db.MemberIntroChangeLog.AddAsync(log, ct);

        member.SetIntro(intro);

        await db.SaveChangesAsync(ct);

        return Result.Success();
    }
}
