using Dapper;
using GestionIntegral.Api.Models.Usuarios;
using System.Data;

namespace GestionIntegral.Api.Data.Repositories.Usuarios
{
    public class AuthRepository : IAuthRepository
    {
        private readonly DbConnectionFactory _connectionFactory;
        private readonly ILogger<AuthRepository> _logger;

        public AuthRepository(DbConnectionFactory connectionFactory, ILogger<AuthRepository> logger)
        {
            _connectionFactory = connectionFactory;
            _logger = logger;
           
        }

        public async Task<Usuario?> GetUserByUsernameAsync(string username)
        {
            var sql = @"SELECT Id, [User], ClaveHash, ClaveSalt, Habilitada,
                        SupAdmin, Nombre, Apellido, IdPerfil, VerLog, DebeCambiarClave
                        FROM gral_Usuarios
                        WHERE [User] = @Username";

            try
            {
                using (var connection = _connectionFactory.CreateConnection())
                {
                    var user = await connection.QuerySingleOrDefaultAsync<Usuario>(sql, new { Username = username });
                    return user;
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error fetching user by username: {ex.Message}");
                return null;
            }
        }

        public async Task<Usuario?> GetUserByIdAsync(int userId)
        {
            var sql = @"SELECT Id, [User], ClaveHash, ClaveSalt, Habilitada,
                         SupAdmin, Nombre, Apellido, IdPerfil, VerLog, DebeCambiarClave
                        FROM gral_Usuarios
                        WHERE Id = @UserId";
            try
            {
                using (var connection = _connectionFactory.CreateConnection())
                {
                    var user = await connection.QuerySingleOrDefaultAsync<Usuario>(sql, new { UserId = userId });
                    Console.WriteLine($"Repo - User {user?.Id} - DebeCambiarClave leído de BD: {user?.DebeCambiarClave}");
                    return user;
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error fetching user by ID: {ex.Message}");
                return null;
            }
        }

        public async Task<bool> UpdatePasswordAsync(int userId, string newHash, string newSalt)
        {
            // Actualiza hash, salt y pone DebeCambiarClave a 0 (false)
            var sql = @"UPDATE dbo.gral_Usuarios
                        SET ClaveHash = @HashedPassword, ClaveSalt = @Salt, DebeCambiarClave = 0
                        WHERE Id = @UserId";

            try
            {
                using (var connection = _connectionFactory.CreateConnection())
                {
                    var parameters = new
                    {
                        HashedPassword = newHash,
                        Salt = newSalt,
                        UserId = userId
                    };
                    int rowsAffected = await connection.ExecuteAsync(sql, parameters);
                    return rowsAffected == 1; // Devuelve true si se actualizó exactamente una fila
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error updating password for user {userId}: {ex.Message}");
                return false;
            }
        }
        public async Task<IEnumerable<string>> GetPermisosCodAccByPerfilIdAsync(int idPerfil)
        {
            // Esta consulta es similar a la que tenías en gestion.vb -> verPermisosPerfil
            var sql = @"
        SELECT p.codAcc
        FROM dbo.gral_Perfiles pf
        INNER JOIN dbo.gral_PermisosPerfiles pp ON pf.id = pp.idPerfil
        INNER JOIN dbo.gral_Permisos p ON pp.idPermiso = p.id
        WHERE pf.id = @IdPerfil;";
            try
            {
                using (var connection = _connectionFactory.CreateConnection())
                {
                    return await connection.QueryAsync<string>(sql, new { IdPerfil = idPerfil });
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error al obtener códigos de acceso para el perfil ID: {IdPerfil}", idPerfil); // Asumiendo que tienes _logger en AuthRepository
                return Enumerable.Empty<string>();
            }
        }
    }
}