using Dapper;
using FastEndpoints;
using Npgsql;

namespace Modules.ERP.Inventory.Search;

public sealed class InventoryHistoryRequest { public Guid ItemId { get; init; } public int PageSize { get; init; } = 100; }
public sealed record InventoryHistoryRow(Guid EntryId, DateTimeOffset OccurredAt, string BusinessType, string ReferenceNo, string WarehouseName, string LocationCode, decimal InboundQty, decimal OutboundQty, decimal BalanceQty, string Actor);
public sealed record InventoryHistoryResponse(IReadOnlyList<InventoryHistoryRow> Items);

public sealed class HistoryEndpoint(NpgsqlDataSource dataSource) : Endpoint<InventoryHistoryRequest, InventoryHistoryResponse>
{
    public override void Configure() { Get("/api/erp/inventory/{itemId}/history"); Permissions("erp.inventory.read"); }

    public override async Task HandleAsync(InventoryHistoryRequest req, CancellationToken ct)
    {
        var pageSize=Math.Clamp(req.PageSize,1,500);
        const string sql="""
        select entry_id as EntryId, occurred_at as OccurredAt, business_type as BusinessType,
               reference_no as ReferenceNo, warehouse_name as WarehouseName,
               coalesce(location_code,'-') as LocationCode, inbound_qty as InboundQty,
               outbound_qty as OutboundQty, balance_qty as BalanceQty, actor as Actor
          from erp_inventory_ledger_projection
         where item_id=@ItemId
         order by occurred_at desc, entry_id
         limit @PageSize;
        """;
        await using var connection=await dataSource.OpenConnectionAsync(ct);
        var items=(await connection.QueryAsync<InventoryHistoryRow>(new CommandDefinition(sql,new{req.ItemId,PageSize=pageSize},cancellationToken:ct))).AsList();
        await Send.OkAsync(new InventoryHistoryResponse(items),ct);
    }
}
