using System.Security.Claims;
using FastEndpoints;
using Microsoft.EntityFrameworkCore;
using TrackQrApi.Data;
using TrackQrApi.Features.Workspaces.Common;

namespace TrackQrApi.Features.Workspaces.Endpoints;

public class ListWorkspacesEndpoint(AppDbContext db)
    : EndpointWithoutRequest<WorkspaceListResponse>
{
    public override void Configure()
    {
        Get("/workspaces");
    }

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

        var workspaces = await db.Workspaces
            .Where(w => w.OwnerUserId == userId)
            .OrderByDescending(w => w.CreatedAt)
            .Select(w => new WorkspaceResponse(
                w.Id,
                w.Name,
                w.Plan.ToString(),
                w.CreatedAt
            ))
            .ToListAsync(ct);

        await HttpContext.Response.SendAsync(new WorkspaceListResponse(workspaces), cancellation: ct);
    }
}