using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using LevelCode.License.Models;

namespace LevelCode.License.DataAccess
{
    public class LicencaLogDAL
    {
        private readonly DbConexao _db;

        public LicencaLogDAL(DbConexao db)
        {
            _db = db;
        }

        // =========================
        // INSERIR LOG
        // =========================
        public void Inserir(ModeloLicencaLog modelo)
        {
            SqlCommand cmd = new SqlCommand(
                @"INSERT INTO Licencas_Log
                  (LicencaId, Acao, DataHora, IpCliente, Detalhes, HWID_Hash)
                  VALUES
                  (@LicencaId, @Acao, @DataHora, @IpCliente, @Detalhes, @HWID_Hash)",
                _db.Conexao);

            cmd.Parameters.AddWithValue("@LicencaId", (object)modelo.LicencaId ?? DBNull.Value);
            cmd.Parameters.AddWithValue("@Acao", (object)modelo.Acao ?? DBNull.Value);
            cmd.Parameters.AddWithValue("@DataHora", modelo.DataHora);
            cmd.Parameters.AddWithValue("@IpCliente", (object)modelo.IpCliente ?? DBNull.Value);
            cmd.Parameters.AddWithValue("@Detalhes", (object)modelo.Detalhes ?? DBNull.Value);
            cmd.Parameters.AddWithValue("@HWID_Hash", (object)modelo.HWID_Hash ?? DBNull.Value);

            _db.Abrir();
            cmd.ExecuteNonQuery();
            _db.Fechar();
        }

        // =========================
        // BUSCAR LOGS POR LICENÇA
        // =========================
        public List<ModeloLicencaLog> BuscarPorLicenca(int licencaId)
        {
            SqlCommand cmd = new SqlCommand(
                @"SELECT * FROM Licencas_Log
                  WHERE LicencaId = @LicencaId
                  ORDER BY DataHora DESC",
                _db.Conexao);

            cmd.Parameters.AddWithValue("@LicencaId", licencaId);

            List<ModeloLicencaLog> lista = new List<ModeloLicencaLog>();

            _db.Abrir();
            SqlDataReader dr = cmd.ExecuteReader();

            while (dr.Read())
            {
                lista.Add(Mapear(dr));
            }

            dr.Close();
            _db.Fechar();

            return lista;
        }

        // =========================
        // MAPEAR DATAREADER → MODELO
        // =========================
        private ModeloLicencaLog Mapear(SqlDataReader dr)
        {
            return new ModeloLicencaLog
            {
                Id = Convert.ToInt32(dr["Id"]),
                LicencaId = dr["LicencaId"] != DBNull.Value
                    ? (int?)Convert.ToInt32(dr["LicencaId"])
                    : null,
                Acao = dr["Acao"] as string,
                DataHora = Convert.ToDateTime(dr["DataHora"]),
                IpCliente = dr["IpCliente"] as string,
                Detalhes = dr["Detalhes"] as string,
                HWID_Hash = dr["HWID_Hash"] as string
            };
        }
    }
}
