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

namespace TrackQrApi.Features.Workspaces.Endpoints;

public class GetWorkspaceRequest
{
    public Guid Id { get; set; }
}

public class GetWorkspaceEndpoint(AppDbContext db)
    : Endpoint<GetWorkspaceRequest, WorkspaceResponse>
{
    public override void Configure()
    {
        Get("/workspaces/{Id}");
    }

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

        var workspace = await db.Workspaces
            .Where(w => w.Id == req.Id && w.OwnerUserId == userId)
            .Select(w => new WorkspaceResponse(
                w.Id,
                w.Name,
                w.Plan.ToString(),
                w.CreatedAt
            ))
            .FirstOrDefaultAsync(ct);

        if (workspace is null)
        {
            await HttpContext.Response.SendAsync(new MessageResponse("Workspace not found"), 404, cancellation: ct);
            return;
        }

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