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

namespace TrackQrApi.Features.ApiKeys.Endpoints;

public class ListApiKeysRequest
{
    public Guid WorkspaceId { get; set; }
}

public class ApiKeyDto
{
    public required Guid Id { get; set; }
    public required string Name { get; set; }
    public required string KeyPrefix { get; set; }
    public List<string>? Scopes { get; set; }
    public DateTime? ExpiresAt { get; set; }
    public DateTime? LastUsedAt { get; set; }
    public DateTime CreatedAt { get; set; }
    public bool IsActive { get; set; }
}

public class ListApiKeysResponse
{
    public required List<ApiKeyDto> ApiKeys { get; set; }
}

public class ListApiKeysEndpoint(AppDbContext db)
    : Endpoint<ListApiKeysRequest, ListApiKeysResponse>
{
    public override void Configure()
    {
        Get("/workspaces/{WorkspaceId}/TrackQrApi-keys");
    }

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

        // Verify workspace ownership
        var workspaceExists = await db.Workspaces
            .AnyAsync(w => w.Id == req.WorkspaceId && w.OwnerUserId == userId, ct);

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

        var apiKeys = await db.ApiKeys
            .Where(k => k.WorkspaceId == req.WorkspaceId)
            .OrderByDescending(k => k.CreatedAt)
            .Select(k => new ApiKeyDto
            {
                Id = k.Id,
                Name = k.Name,
                KeyPrefix = k.KeyPrefix,
                Scopes = k.Scopes,
                ExpiresAt = k.ExpiresAt,
                LastUsedAt = k.LastUsedAt,
                CreatedAt = k.CreatedAt,
                IsActive = k.IsActive
            })
            .ToListAsync(ct);

        var response = new ListApiKeysResponse { ApiKeys = apiKeys };
        await HttpContext.Response.SendAsync(response, cancellation: ct);
    }
}