using System;
using System.Data.SqlClient;

namespace Levelcode_licenseCliente.DataAccess
{
    public class LicencaMaquinaClienteDAL
    {
        private readonly string _connectionString;

        public LicencaMaquinaClienteDAL(string connectionString)
        {
            _connectionString = connectionString;
        }

        public int ContarMaquinasAtivas(int licencaId)
        {
            using (SqlConnection conn = new SqlConnection(_connectionString))
            {
                SqlCommand cmd = new SqlCommand(
                    @"SELECT COUNT(*)
                      FROM Licencas_Maquinas
                      WHERE LicencaId = @LicencaId
                        AND Status = 1",
                    conn);

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

                conn.Open();
                return Convert.ToInt32(cmd.ExecuteScalar());
            }
        }

        public bool MaquinaJaRegistrada(int licencaId, string hwid)
        {
            using (SqlConnection conn = new SqlConnection(_connectionString))
            {
                SqlCommand cmd = new SqlCommand(
                    @"SELECT COUNT(*)
                      FROM Licencas_Maquinas
                      WHERE LicencaId = @LicencaId
                        AND HWID = @HWID
                        AND Status = 1",
                    conn);

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

                conn.Open();
                return Convert.ToInt32(cmd.ExecuteScalar()) > 0;
            }
        }

        public void RegistrarMaquina(int licencaId, string hwid)
        {
            using (SqlConnection conn = new SqlConnection(_connectionString))
            {
                SqlCommand cmd = new SqlCommand(
                    @"INSERT INTO Licencas_Maquinas
                      (LicencaId, HWID, Status, DataAtivacao)
                      VALUES
                      (@LicencaId, @HWID, 1, GETDATE())",
                    conn);

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

                conn.Open();
                cmd.ExecuteNonQuery();
            }
        }
    }
}
