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

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

        if (string.IsNullOrWhiteSpace(name))
        {
            return Result.Failure(Error.Problem("MyPage.NameRequired", "별명은 필수입니다."));
        }

        if (name.Length > 40)
        {
            return Result.Failure(Error.Problem("MyPage.NameTooLong", "별명은 40자 이하여야 합니다."));
        }

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

        // Config 로드
        var accountConfig = await AccountConfigLoader.GetAccountConfigAsync(cache, db, ct);

        // 별명 변경 주기 확인
        if (accountConfig.ChangeNameDay is > 0 && member.LastNameChangedAt.HasValue)
        {
            var nextChangeDate = member.LastNameChangedAt.Value.AddDays(accountConfig.ChangeNameDay.Value);
            if (DateTime.UtcNow < nextChangeDate)
            {
                return Result.Failure(Error.Problem("MyPage.NameChangeTooSoon",
                    $"별명은 {accountConfig.ChangeNameDay}일마다 변경 가능합니다."));
            }
        }

        // 금지 별명 확인
        if (!string.IsNullOrWhiteSpace(accountConfig.DeniedNameList))
        {
            var deniedNames = accountConfig.DeniedNameList
                .Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries)
                .Select(n => n.ToLower());

            if (deniedNames.Contains(name.ToLower()))
            {
                return Result.Failure(Error.Problem("MyPage.DeniedName", "사용할 수 없는 별명입니다."));
            }
        }

        var nameExists = await db.Member.AnyAsync(m => m.Name == name && m.ID != request.MemberID, ct);
        if (nameExists)
        {
            return Result.Failure(Error.Conflict("MyPage.NameExists", "이미 사용 중인 별명입니다."));
        }

        var log = MemberNameChangeLog.Create(request.MemberID, member.Name, name);
        await db.MemberNameChangeLog.AddAsync(log, ct);

        member.SetName(name);

        await db.SaveChangesAsync(ct);

        return Result.Success();
    }
}
