using Application.Abstractions.Messaging;
using Web.Api.Extensions;
using Web.Api.Common;
using Domain.Entities.EmailVerification.ValueObject;

namespace Web.Api.Endpoints.Auth;

internal sealed class VerifyEmail : IEndpoint
{
    public sealed record Request(string Email, string Code, VerificationType Type);

    public void MapEndpoint(IEndpointRouteBuilder app)
    {
        // 이메일 인증번호 검증
        app.MapPost("api/auth/verify-email", async (
            Request request,
            HttpContext httpContext,
            ISender sender,
            CancellationToken ct
        ) =>
        {
            var command = new Application.Features.Api.Auth.VerifyEmail.Command(
                request.Email,
                request.Code,
                request.Type
            );

            var result = await sender.Send(command, ct);

            if (result.IsSuccess)
            {
                // 인증 타입별 쿠키 설정
                var cookieOptions = new CookieOptions
                {
                    HttpOnly = true,
                    Secure = true,
                    SameSite = SameSiteMode.None,
                    Expires = result.Value switch
                    {
                        VerificationType.Registration   => DateTime.UtcNow.AddMinutes(5),
                        VerificationType.ForgotPassword => DateTime.UtcNow.AddMinutes(10),
                        _                               => DateTime.UtcNow.AddMinutes(5)
                    }
                };

                // 사전 인증 완료 쿠키 설정 (예: isVerified-Registration, isVerified-ForgotPassword)
                httpContext.Response.Cookies.Append(
                    $"isVerified-{result.Value}",
                    "true",
                    cookieOptions
                );
            }

            return result.Match(
                _ => ApiResponse.Ok(new { message = "이메일 인증 성공" }),
                CustomResults.Problem
            );
        })
        .WithTags("Auth")
        .AllowAnonymous();
    }
}