using FastEndpoints;
using FluentValidation;
using Microsoft.EntityFrameworkCore;
using TrackQrApi.Data;
using TrackQrApi.Features.Auth.Common;

namespace TrackQrApi.Features.Auth.Endpoints;

public class VerifyEmailRequest
{
    public string Token { get; set; } = string.Empty;
}

public class VerifyEmailValidator : Validator<VerifyEmailRequest>
{
    public VerifyEmailValidator()
    {
        RuleFor(x => x.Token).NotEmpty().WithMessage("Token is required");
    }
}

public class VerifyEmailEndpoint(AppDbContext db) : Endpoint<VerifyEmailRequest>
{
    public override void Configure()
    {
        Post("/auth/verify-email");
        AllowAnonymous();
    }

    public override async Task HandleAsync(VerifyEmailRequest req, CancellationToken ct)
    {
        var token = await db.EmailVerificationTokens
            .Include(t => t.User)
            .FirstOrDefaultAsync(t => t.Token == req.Token, ct);

        if (token == null)
        {
            await HttpContext.Response.SendAsync(new MessageResponse("Invalid verification token"), 400,
                cancellation: ct);
            return;
        }

        if (token.ExpiresAt < DateTime.UtcNow)
        {
            db.EmailVerificationTokens.Remove(token);
            await db.SaveChangesAsync(ct);
            await HttpContext.Response.SendAsync(new MessageResponse("Verification token has expired"), 400,
                cancellation: ct);
            return;
        }

        // Mark user as verified
        token.User.VerifiedAt = DateTime.UtcNow;

        // Remove the token
        db.EmailVerificationTokens.Remove(token);
        await db.SaveChangesAsync(ct);

        await HttpContext.Response.SendAsync(new MessageResponse("Email verified successfully"), cancellation: ct);
    }
}