using System.Security.Claims;
using FastEndpoints;
using FluentValidation;
using TrackQrApi.Data;
using TrackQrApi.Features.Auth.Common;
using TrackQrApi.Features.Plans.Services;
using TrackQrApi.Features.Workspaces.Common;
using TrackQrApi.Models;

namespace TrackQrApi.Features.Workspaces.Endpoints;

public class CreateWorkspaceRequest
{
    public string Name { get; set; } = string.Empty;
}

public class CreateWorkspaceValidator : Validator<CreateWorkspaceRequest>
{
    public CreateWorkspaceValidator()
    {
        RuleFor(x => x.Name)
            .NotEmpty().WithMessage("Name is required")
            .MaximumLength(100).WithMessage("Name must not exceed 100 characters");
    }
}

public class CreateWorkspaceEndpoint(AppDbContext db, IPlanLimitsService planLimits)
    : Endpoint<CreateWorkspaceRequest, WorkspaceResponse>
{
    public override void Configure()
    {
        Post("/workspaces");
    }

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

        // Check plan limits
        if (!await planLimits.CanCreateWorkspaceAsync(userId, ct))
        {
            await HttpContext.Response.SendAsync(
                new MessageResponse("Workspace limit reached. Please upgrade your plan to create more workspaces."),
                402,
                cancellation: ct);
            return;
        }

        var workspace = new Workspace
        {
            Id = Guid.NewGuid(),
            OwnerUserId = userId,
            Name = req.Name,
            Plan = WorkspacePlan.Free,
            CreatedAt = DateTime.UtcNow
        };

        db.Workspaces.Add(workspace);
        await db.SaveChangesAsync(ct);

        var response = new WorkspaceResponse(
            workspace.Id,
            workspace.Name,
            workspace.Plan.ToString(),
            workspace.CreatedAt
        );

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