using Dapper;
using FastEndpoints;
using Npgsql;

namespace Modules.ERP.Inventory.Search;

public sealed class LocationsRequest { public Guid ItemId { get; init; } }
public sealed record InventoryLocationRow(string Key, string WarehouseName, string LocationCode, decimal OnHandQty, decimal AllocatedQty, decimal AvailableQty, decimal HoldQty);
public sealed record InventoryLocationsResponse(IReadOnlyList<InventoryLocationRow> Items);

public sealed class LocationsEndpoint(NpgsqlDataSource dataSource) : Endpoint<LocationsRequest, InventoryLocationsResponse>
{
    public override void Configure()
    {
        Get("/api/erp/inventory/{itemId}/locations");
        Permissions("erp.inventory.read");
    }

    public override async Task HandleAsync(LocationsRequest req, CancellationToken ct)
    {
        const string sql = """
        select snapshot_key as Key,
               warehouse_name as WarehouseName,
               coalesce(location_code, '-') as LocationCode,
               on_hand_qty as OnHandQty,
               allocated_qty as AllocatedQty,
               available_qty as AvailableQty,
               hold_qty as HoldQty
        from erp_inventory_snapshot_projection
        where item_id = @ItemId
        order by warehouse_name, location_code nulls first;
        """;
        await using var connection = await dataSource.OpenConnectionAsync(ct);
        var items = (await connection.QueryAsync<InventoryLocationRow>(new CommandDefinition(sql, new { req.ItemId }, cancellationToken: ct))).AsList();
        await Send.OkAsync(new InventoryLocationsResponse(items), ct);
    }
}
