using Dapper;
using FastEndpoints;
using Npgsql;

namespace Modules.OMS.Lookups.Customers;

public sealed class ResolveByCodeEndpoint(NpgsqlDataSource dataSource) : EndpointWithoutRequest
{
    public override void Configure()
    {
        Get("/api/lookups/customers/by-code/{code}");
        Permissions("oms.order.read");
    }

    public override async Task HandleAsync(CancellationToken ct)
    {
        var code = Route<string>("code");
        await using var connection = await dataSource.OpenConnectionAsync(ct);
        var item = await connection.QuerySingleOrDefaultAsync(new CommandDefinition(@"
select id, code, name as DisplayName, case when is_active then '사용' else '중지' end as Status
from oms.customers where code=@Code and is_active=true;", new { Code = code }, cancellationToken: ct));
        if (item is null) { await Send.NotFoundAsync(ct); return; }
        await Send.OkAsync(item, ct);
    }
}
