using Data.Entities;
using System.Configuration;
using Microsoft.Data.SqlClient;
using Microsoft.EntityFrameworkCore;
using Microsoft.IdentityModel.Protocols;
using Microsoft.Extensions.Configuration;

namespace Data.Models
{
    public class OperationsHubContext : DbContext
    {
        // Constructor que permite la inyección de dependencias
        public OperationsHubContext(DbContextOptions<OperationsHubContext> options) : base(options)
        {
        }

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            if (!optionsBuilder.IsConfigured)
            {
                // Leer la cadena de conexión desde app.config
                var connectionString = ConfigurationManager.ConnectionStrings["OperationsHub"]?.ConnectionString;
                if (connectionString == null)
                {
                    throw new InvalidOperationException("No se encontró la cadena de conexión 'OperationsHub'.");
                }
                optionsBuilder.UseSqlServer(connectionString);
                // Prueba de conexión: Intento de apertura de conexión
                using (var connection = new SqlConnection(connectionString))
                {
                    connection.Open(); // Lanza excepción si falla
                    System.Diagnostics.Debug.WriteLine("Conexión a la base de datos exitosa.");
                    connection.Close();
                }
            }
        }
        public bool TestConnection(string connectionString)
        {
            using (var connection = new SqlConnection(connectionString))
            {
                try
                {
                    connection.Open();
                    return true; // Conexión exitosa
                }
                catch (Exception ex)
                {
                    // Manejar la excepción, tal vez loguearla
                    Console.WriteLine($"Error al conectar: {ex.Message}");
                    return false; // Conexión fallida
                }
            }
        }

        public DbSet<PhOH_Tickets> Tickets { get; set; }
        public DbSet<Tickets_Dashboard_Result> TicketsDashboardResults { get; set; }
        public DbSet<Tickets_GetSummary_Result> TicketsSummaryResults { get; set; }

        public async Task<List<Tickets_Dashboard_Result>> Tickets_DashboardAsync(string estadoParam, string ordenParam)
        {
            var estadoParamSql = new SqlParameter("@EstadoParam", estadoParam ?? (object)DBNull.Value);
            var ordenParamSql = new SqlParameter("@OrdenParam", ordenParam ?? (object)DBNull.Value);

            // Consulta usando FromSqlRaw sobre el DbSet correspondiente
            return await TicketsDashboardResults
                .FromSqlRaw("EXEC Tickets_Dashboard @EstadoParam, @OrdenParam", estadoParamSql, ordenParamSql)
                .ToListAsync();
        }

        public async Task<List<Tickets_GetSummary_Result>> Tickets_GetSummaryAsync()
        {
            // Consulta usando FromSqlRaw sobre el DbSet correspondiente
            return await TicketsSummaryResults
                .FromSqlRaw("EXEC Tickets_GetSummary")
                .ToListAsync();
        }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.Entity<PhOH_Tickets>().ToTable("PhOH_Tickets");

            // Marcar los DbSet de resultados como entidades de solo lectura
            modelBuilder.Entity<Tickets_Dashboard_Result>().HasNoKey();
            modelBuilder.Entity<Tickets_GetSummary_Result>().HasNoKey();
        }
    }
}