using Dapper;
using Npgsql;

namespace Books.Api.EventFlow.Repositories;

public class ManufacturerRepository(NpgsqlDataSource dataSource) : IManufacturerRepository
{
    public async Task<IReadOnlyList<string>> GetManufacturersAsync(
        string companyId,
        string? searchTerm = null,
        int limit = 20,
        CancellationToken cancellationToken = default)
    {
        await using var connection = await dataSource.OpenConnectionAsync(cancellationToken);

        string sql;
        object parameters;

        if (string.IsNullOrWhiteSpace(searchTerm))
        {
            sql = """
                SELECT DISTINCT manufacturer
                FROM product_read_models
                WHERE company_id = @CompanyId
                  AND manufacturer IS NOT NULL
                  AND manufacturer != ''
                ORDER BY manufacturer
                LIMIT @Limit
                """;
            parameters = new { CompanyId = companyId, Limit = limit };
        }
        else
        {
            sql = """
                SELECT DISTINCT manufacturer
                FROM product_read_models
                WHERE company_id = @CompanyId
                  AND manufacturer IS NOT NULL
                  AND manufacturer != ''
                  AND manufacturer ILIKE @SearchPattern
                ORDER BY manufacturer
                LIMIT @Limit
                """;
            parameters = new { CompanyId = companyId, SearchPattern = $"%{searchTerm}%", Limit = limit };
        }

        var result = await connection.QueryAsync<string>(sql, parameters);
        return result.ToList();
    }
}
