using Dapper;
using Npgsql;

namespace Books.Api.EventFlow.Repositories;

public class ApiKeyRepository(NpgsqlDataSource dataSource) : IApiKeyRepository
{
    public async Task<ApiKeyValidationDto?> GetByIdForValidationAsync(
        string apiKeyId,
        CancellationToken cancellationToken = default)
    {
        await using var connection = await dataSource.OpenConnectionAsync(cancellationToken);

        const string sql = """
            SELECT
                aggregate_id AS ApiKeyId,
                name AS Name,
                key_hash AS KeyHash,
                company_id AS CompanyId,
                is_active AS IsActive
            FROM apikey_read_models
            WHERE aggregate_id = @ApiKeyId
              AND is_active = true
            """;

        return await connection.QuerySingleOrDefaultAsync<ApiKeyValidationDto>(
            sql,
            new { ApiKeyId = apiKeyId });
    }

    public async Task<IReadOnlyList<ApiKeyDto>> GetByCompanyIdAsync(
        string companyId,
        CancellationToken cancellationToken = default)
    {
        await using var connection = await dataSource.OpenConnectionAsync(cancellationToken);

        const string sql = """
            SELECT
                aggregate_id AS Id,
                name AS Name,
                company_id AS CompanyId,
                created_by AS CreatedBy,
                create_time AS CreatedAt,
                is_active AS IsActive,
                revoked_time AS RevokedAt,
                revoked_by AS RevokedBy
            FROM apikey_read_models
            WHERE company_id = @CompanyId
            ORDER BY create_time DESC
            """;

        var result = await connection.QueryAsync<ApiKeyDto>(sql, new { CompanyId = companyId });
        return result.ToList();
    }
}
