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

namespace TrackQrApi.Features.Assets.Endpoints;

public class GetAssetRequest
{
    public string StorageKey { get; set; } = string.Empty;
}

public class GetAssetEndpoint(AppDbContext db, IAssetStorageService storage)
    : Endpoint<GetAssetRequest>
{
    public override void Configure()
    {
        Get("/assets/{StorageKey}");
        AllowAnonymous(); // Public access to assets
    }

    public override async Task HandleAsync(GetAssetRequest req, CancellationToken ct)
    {
        // Verify asset exists in database
        var asset = await db.Assets
            .FirstOrDefaultAsync(a => a.StorageKey == req.StorageKey, ct);

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

        // Get file from storage
        var result = await storage.GetAsync(req.StorageKey);

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

        var (stream, contentType) = result.Value;

        // Set cache headers
        HttpContext.Response.Headers.CacheControl = "public, max-age=31536000"; // 1 year
        HttpContext.Response.ContentType = contentType;

        await stream.CopyToAsync(HttpContext.Response.Body, ct);
        await stream.DisposeAsync();
    }
}