using Dapper;
using MieSystem.Data.Interfaces;
using Npgsql;
using System.Data;

namespace MieSystem.Data.Repositories
{
    public class DatabaseConnectionFactory : IDatabaseConnectionFactory
    {
        private readonly IConfiguration _configuration;
        private readonly string? _connectionString;

        public DatabaseConnectionFactory(IConfiguration configuration)
        {
            _configuration = configuration;
            _connectionString = _configuration.GetConnectionString("PostgreSQL");

            // Mapear tipos de PostgreSQL a .NET
            Dapper.DefaultTypeMap.MatchNamesWithUnderscores = true;
            NpgsqlConnection.GlobalTypeMapper.UseJsonNet();

        }

        public IDbConnection CreateConnection()
        {
            var connection = new NpgsqlConnection(_connectionString);

            // Configuración adicional
            connection.Open();
            connection.ReloadTypes(); // Para tipos custom de PostgreSQL

            return connection;
        }

        public async Task<IDbConnection> CreateConnectionAsync()
        {
            var connection = new NpgsqlConnection(_connectionString);

            await connection.OpenAsync();
            await connection.ReloadTypesAsync();

            return connection;
        }
    }
}
