using Dapper;
using FastEndpoints;
using Npgsql;
using Modules.ERP.Items.Search;

namespace Modules.ERP.Items.Get;

public sealed class Request { public Guid Id { get; init; } }

public sealed class Endpoint(NpgsqlDataSource dataSource) : Endpoint<Request, ItemMasterRow>
{
    public override void Configure()
    {
        Get("/api/erp/items/{id}");
        Permissions("erp.item.read");
    }

    public override async Task HandleAsync(Request req, CancellationToken ct)
    {
        const string sql = """
        select id, code, name, category_name as CategoryName, specification, unit, barcode,
               default_warehouse_id as DefaultWarehouseId, default_warehouse_name as DefaultWarehouseName,
               lot_managed as LotManaged, expiry_managed as ExpiryManaged, active, version
        from erp_item_search_projection
        where id = @Id;
        """;
        await using var connection = await dataSource.OpenConnectionAsync(ct);
        var row = await connection.QuerySingleOrDefaultAsync<ItemMasterRow>(new CommandDefinition(sql, new { req.Id }, cancellationToken: ct));
        if (row is null) { await Send.NotFoundAsync(ct); return; }
        await Send.OkAsync(row, ct);
    }
}
