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

namespace TrackQrApi.Features.Assets.Endpoints;

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

public class ListAssetsEndpoint(AppDbContext db, IAssetStorageService storage)
    : Endpoint<ListAssetsRequest, AssetListResponse>
{
    public override void Configure()
    {
        Get("/workspaces/{WorkspaceId}/assets");
    }

    public override async Task HandleAsync(ListAssetsRequest 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 assets = await db.Assets
            .Where(a => a.WorkspaceId == req.WorkspaceId)
            .OrderByDescending(a => a.CreatedAt)
            .ToListAsync(ct);

        var response = new AssetListResponse(
            assets.Select(a => new AssetResponse(
                a.Id,
                a.WorkspaceId,
                a.Type.ToString(),
                a.Mime,
                a.Size,
                storage.GetPublicUrl(a.StorageKey, HttpContext),
                a.CreatedAt
            ))
        );

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