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

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

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

        // =========================
        // REGISTRAR MÁQUINA
        // =========================
        public int Inserir(ModeloLicencaMaquina modelo)
        {
            SqlCommand cmd = new SqlCommand(
                @"INSERT INTO Licencas_Maquinas
                  (LicencaId, HWID, HWID_Hash, PrimeiroUso, UltimoUso, DataAtivacao, Status)
                  VALUES
                  (@LicencaId, @HWID, @HWID_Hash, @PrimeiroUso, @UltimoUso, @DataAtivacao, @Status);
                  SELECT SCOPE_IDENTITY();",
                _db.Conexao);

            cmd.Parameters.AddWithValue("@LicencaId", modelo.LicencaId);
            cmd.Parameters.AddWithValue("@HWID", (object)modelo.HWID ?? DBNull.Value);
            cmd.Parameters.AddWithValue("@HWID_Hash", (object)modelo.HWID_Hash ?? DBNull.Value);
            cmd.Parameters.AddWithValue("@PrimeiroUso", modelo.PrimeiroUso);
            cmd.Parameters.AddWithValue("@UltimoUso", modelo.UltimoUso);
            cmd.Parameters.AddWithValue("@DataAtivacao", (object)modelo.DataAtivacao ?? DBNull.Value);
            cmd.Parameters.AddWithValue("@Status", modelo.Status);

            _db.Abrir();
            int id = Convert.ToInt32(cmd.ExecuteScalar());
            _db.Fechar();

            return id;
        }

        // =========================
        // BUSCAR MÁQUINA POR LICENÇA + HWID
        // =========================
        public ModeloLicencaMaquina BuscarPorLicencaEHash(int licencaId, string hwidHash)
        {
            SqlCommand cmd = new SqlCommand(
                @"SELECT * FROM Licencas_Maquinas
                  WHERE LicencaId = @LicencaId
                    AND HWID_Hash = @HWID_Hash",
                _db.Conexao);

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

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

            ModeloLicencaMaquina modelo = null;

            if (dr.Read())
            {
                modelo = Mapear(dr);
            }

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

            return modelo;
        }

        // =========================
        // CONTAR MÁQUINAS ATIVAS
        // =========================
        public int ContarMaquinasAtivas(int licencaId)
        {
            SqlCommand cmd = new SqlCommand(
                @"SELECT COUNT(*)
                  FROM Licencas_Maquinas
                  WHERE LicencaId = @LicencaId
                    AND Status = 1",
                _db.Conexao);

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

            _db.Abrir();
            int total = Convert.ToInt32(cmd.ExecuteScalar());
            _db.Fechar();

            return total;
        }

        // =========================
        // ATUALIZAR ÚLTIMO USO
        // =========================
        public void AtualizarUltimoUso(int id)
        {
            SqlCommand cmd = new SqlCommand(
                @"UPDATE Licencas_Maquinas
                  SET UltimoUso = GETDATE()
                  WHERE Id = @Id",
                _db.Conexao);

            cmd.Parameters.AddWithValue("@Id", id);

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

        // =========================
        // ATUALIZAR STATUS DA MÁQUINA
        // =========================
        public void AtualizarStatus(int id, int status)
        {
            SqlCommand cmd = new SqlCommand(
                @"UPDATE Licencas_Maquinas
                  SET Status = @Status
                  WHERE Id = @Id",
                _db.Conexao);

            cmd.Parameters.AddWithValue("@Status", status);
            cmd.Parameters.AddWithValue("@Id", id);

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

        // =========================
        // MAPEAR DATAREADER → MODELO
        // =========================
        public List<ModeloLicencaMaquina> ListarPorLicenca(int licencaId)
        {
            List<ModeloLicencaMaquina> lista = new List<ModeloLicencaMaquina>();

            SqlCommand cmd = new SqlCommand(
                @"SELECT 
            Id,
            LicencaId,
            HWID,
            HWID_Hash,
            PrimeiroUso,
            UltimoUso,
            DataAtivacao,
            Status
          FROM Licencas_Maquinas
          WHERE LicencaId = @LicencaId
          ORDER BY PrimeiroUso",
                _db.Conexao);

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

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

            while (dr.Read())
            {
                lista.Add(new ModeloLicencaMaquina
                {
                    Id = Convert.ToInt32(dr["Id"]),
                    LicencaId = Convert.ToInt32(dr["LicencaId"]),
                    HWID = dr["HWID"].ToString(),
                    HWID_Hash = dr["HWID_Hash"] != DBNull.Value
                        ? dr["HWID_Hash"].ToString()
                        : null,

                    PrimeiroUso = Convert.ToDateTime(dr["PrimeiroUso"]),
                    UltimoUso = Convert.ToDateTime(dr["UltimoUso"]),

                    DataAtivacao = dr["DataAtivacao"] != DBNull.Value
                        ? (DateTime?)Convert.ToDateTime(dr["DataAtivacao"])
                        : null,

                    Status = Convert.ToInt32(dr["Status"])
                });
            }

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

            return lista;
        }
        public void DesativarMaquina(int id)
        {
            SqlCommand cmd = new SqlCommand(
                @"UPDATE Licencas_Maquinas
          SET Status = 0
          WHERE Id = @Id",
                _db.Conexao);

            cmd.Parameters.AddWithValue("@Id", id);

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

        private ModeloLicencaMaquina Mapear(SqlDataReader dr)
        {
            return new ModeloLicencaMaquina
            {
                Id = Convert.ToInt32(dr["Id"]),
                LicencaId = Convert.ToInt32(dr["LicencaId"]),
                HWID = dr["HWID"] as string,
                HWID_Hash = dr["HWID_Hash"] as string,
                PrimeiroUso = Convert.ToDateTime(dr["PrimeiroUso"]),
                UltimoUso = Convert.ToDateTime(dr["UltimoUso"]),
                DataAtivacao = dr["DataAtivacao"] != DBNull.Value
                    ? (DateTime?)Convert.ToDateTime(dr["DataAtivacao"])
                    : null,
                Status = Convert.ToInt32(dr["Status"])
            };
        }
    }
}
