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

namespace TrackQrApi.Features.Projects.Endpoints;

public class GetProjectRequest
{
    public Guid WorkspaceId { get; set; }
    public Guid Id { get; set; }
}

public class GetProjectEndpoint(AppDbContext db)
    : Endpoint<GetProjectRequest, ProjectResponse>
{
    public override void Configure()
    {
        Get("/workspaces/{WorkspaceId}/projects/{Id}");
    }

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

        var project = await db.Projects
            .Where(p => p.Id == req.Id && p.WorkspaceId == req.WorkspaceId && p.Workspace.OwnerUserId == userId)
            .Select(p => new ProjectResponse(
                p.Id,
                p.WorkspaceId,
                p.Name,
                p.Description,
                p.ShortLinks.Count(l => l.DeletedAt == null),
                p.QRCodeDesigns.Count,
                p.CreatedAt
            ))
            .FirstOrDefaultAsync(ct);

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

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