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

namespace TrackQrApi.Features.Workspaces.Endpoints;

public class UpdateWorkspaceRequest
{
    public Guid Id { get; set; }
    public string Name { get; set; } = string.Empty;
}

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

public class UpdateWorkspaceEndpoint(AppDbContext db)
    : Endpoint<UpdateWorkspaceRequest, WorkspaceResponse>
{
    public override void Configure()
    {
        Put("/workspaces/{Id}");
    }

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

        var workspace = await db.Workspaces
            .FirstOrDefaultAsync(w => w.Id == req.Id && w.OwnerUserId == userId, ct);

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

        workspace.Name = req.Name;
        await db.SaveChangesAsync(ct);

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

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