using SharedKernel.Results;
using Application.Abstractions.Data;
using MediatR;
using Microsoft.EntityFrameworkCore;

namespace Application.Features.Api.Auth.GetProfile;

internal sealed class Handler(IAppDbContext db) : IRequestHandler<Query, Result<Response>>
{
    public async Task<Result<Response>> Handle(Query request, CancellationToken ct)
    {
        var member = await db.Member
            .AsNoTracking()
            .Include(m => m.MemberGrade)
            .Include(m => m.MemberApprove)
            .Include(m => m.MemberStats)
            .Where(m => m.ID == request.MemberID)
            .Select(m => new Response(
                m.ID,
                m.SID,
                m.Email,
                m.Name,
                m.Intro,
                m.Summary,
                m.Thumb,
                m.Icon,
                m.Gender != null ? (int?)m.Gender : null,
                m.IsEmailVerified,
                m.IsAuthCertified,
                m.IsAdmin,
                m.IsCreator,
                m.IsDenied,
                m.LastLoginAt,
                m.PasswordUpdatedAt,
                m.CreatedAt,
                m.UpdatedAt,
                m.MemberGrade != null ? new GradeDto(
                    m.MemberGrade.ID,
                    m.MemberGrade.KorName,
                    m.MemberGrade.EngName,
                    m.MemberGrade.Order,
                    m.MemberGrade.Image
                ) : null,
                m.MemberApprove != null ? new ApproveDto(
                    m.MemberApprove.IsReceiveSMS,
                    m.MemberApprove.IsReceiveEmail,
                    m.MemberApprove.IsReceiveNote,
                    m.MemberApprove.IsDisclosureInvest
                ) : new ApproveDto(false, false, false, false),
                m.MemberStats != null ? new StatsDto(
                    m.MemberStats.Exp,
                    m.MemberStats.PostCount,
                    m.MemberStats.CommentCount,
                    m.MemberStats.LikeReceivedCount,
                    m.MemberStats.LikeGivenCount,
                    m.MemberStats.BookmarkGivenCount,
                    m.MemberStats.LoginCount,
                    m.MemberStats.AttendanceCount,
                    m.MemberStats.FollowingCount,
                    m.MemberStats.FollowerCount
                ) : new StatsDto(0, 0, 0, 0, 0, 0, 0, 0, 0, 0)))
            .FirstOrDefaultAsync(ct);

        if (member is null)
        {
            return Result.Failure<Response>(Error.NotFound("Auth.MemberNotFound", "회원 정보를 찾을 수 없습니다."));
        }

        return Result.Success(member);
    }
}