using Dapper;
using FastEndpoints;
using Npgsql;

namespace Modules.OMS.Lookups.Customers;

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

    public override async Task HandleAsync(CancellationToken ct)
    {
        var query = Query<string>("query", false) ?? string.Empty;
        var page = Math.Max(1, Query<int>("page", false));
        var pageSize = Math.Clamp(Query<int>("pageSize", false), 1, 100);
        await using var connection = await dataSource.OpenConnectionAsync(ct);
        var items = (await connection.QueryAsync(new CommandDefinition(@"
select id, code, name as DisplayName, case when is_active then '사용' else '중지' end as Status
from oms.customers
where is_active = true and (@Query = '' or code ilike '%' || @Query || '%' or name ilike '%' || @Query || '%')
order by code
offset @Offset limit @PageSize;", new { Query = query, Offset = (page - 1) * pageSize, PageSize = pageSize }, cancellationToken: ct))).ToArray();
        var count = await connection.ExecuteScalarAsync<int>(new CommandDefinition(@"
select count(*) from oms.customers
where is_active = true and (@Query = '' or code ilike '%' || @Query || '%' or name ilike '%' || @Query || '%');", new { Query = query }, cancellationToken: ct));
        await Send.OkAsync(new { items, totalCount = count }, ct);
    }
}
