using Dapper;
using SIGCM2.Application.Abstractions.Persistence;

namespace SIGCM2.Infrastructure.Persistence;

/// <summary>
/// PRD-002 — Real Dapper implementation of IProductQueryRepository against dbo.Product.
/// Replaces NullProductQueryRepository which was bound during PRD-001.
/// </summary>
public sealed class ProductQueryRepository : IProductQueryRepository
{
    private readonly SqlConnectionFactory _factory;

    public ProductQueryRepository(SqlConnectionFactory factory)
    {
        _factory = factory;
    }

    public async Task<bool> ExistsActiveByProductTypeAsync(int productTypeId, CancellationToken ct = default)
    {
        const string sql = """
            SELECT COUNT(1)
            FROM dbo.Product
            WHERE ProductTypeId = @ProductTypeId
              AND IsActive = 1
            """;

        await using var connection = _factory.CreateConnection();
        await connection.OpenAsync(ct);

        var count = await connection.ExecuteScalarAsync<int>(sql, new { ProductTypeId = productTypeId });
        return count > 0;
    }
}
