using System.Security.Claims;
using FastEndpoints;
using Microsoft.EntityFrameworkCore;
using TrackQrApi.Data;

namespace TrackQrApi.Features.Auth.Endpoints;

public record ProfileResponse(
    Guid Id,
    string Email,
    bool IsVerified,
    DateTime CreatedAt
);

public class GetProfileEndpoint(AppDbContext db) : EndpointWithoutRequest<ProfileResponse>
{
    public override void Configure()
    {
        Get("/auth/profile");
    }

    public override async Task HandleAsync(CancellationToken ct)
    {
        var userId = Guid.Parse(User.FindFirstValue(ClaimTypes.NameIdentifier)!);

        var user = await db.Users
            .Where(u => u.Id == userId)
            .Select(u => new ProfileResponse(
                u.Id,
                u.Email,
                u.VerifiedAt != null,
                u.CreatedAt
            ))
            .FirstOrDefaultAsync(ct);

        if (user == null)
        {
            await HttpContext.Response.SendAsync(new { message = "User not found" }, 404, cancellation: ct);
            return;
        }

        await HttpContext.Response.SendAsync(user, cancellation: ct);
    }
}