using Levelcode_licenseCliente.Models;
using System;
using System.Data.SqlClient;

namespace Levelcode_licenseCliente.DataAccess
{
    public class LicencaClienteDAL
    {
        private readonly string _connectionString;
        private readonly DbConexao _db;
        public LicencaClienteDAL(string connectionString)
        {
            _connectionString = connectionString;
        }

        public ModeloLicenca BuscarPorLicenseKey(string licenseKey)
        {
            using (SqlConnection conn = new SqlConnection(_connectionString))
            {
                SqlCommand cmd = new SqlCommand(
                    @"SELECT *
                      FROM Licencas
                      WHERE LicenseKey = @LicenseKey
                        AND Status = 1",
                    conn);

                cmd.Parameters.AddWithValue("@LicenseKey", licenseKey);

                conn.Open();
                SqlDataReader dr = cmd.ExecuteReader();

                ModeloLicenca licenca = null;

                if (dr.Read())
                {
                    licenca = new ModeloLicenca
                    {
                        IdLicenca = Convert.ToInt32(dr["IdLicenca"]),
                        LicenseKey = dr["LicenseKey"].ToString(),
                        Cliente = dr["Cliente"].ToString(),
                        LimiteMaquinas = Convert.ToInt32(dr["LimiteMaquinas"]),
                        ExpiraEm = dr["ExpiraEm"] != DBNull.Value
                            ? (DateTime?)Convert.ToDateTime(dr["ExpiraEm"])
                            : null,
                        Modulos = dr["Modulos"].ToString()
                    };
                }

                dr.Close();
                return licenca;
            }
        }

        public ModeloLicenca BuscarLicencaAtiva()
        {
            SqlCommand cmd = new SqlCommand(
                @"SELECT TOP 1 *
          FROM Licencas
          WHERE Status = 1
          ORDER BY DataCriacao DESC",
                _db.Conexao);

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

            ModeloLicenca modelo = null;

            if (dr.Read())
            {
                modelo = new ModeloLicenca
                {
                    IdLicenca = Convert.ToInt32(dr["IdLicenca"]),
                    LicenseKey = dr["LicenseKey"].ToString(),
                    Cliente = dr["Cliente"].ToString(),
                    LimiteMaquinas = Convert.ToInt32(dr["LimiteMaquinas"]),
                    ExpiraEm = dr["ExpiraEm"] != DBNull.Value
                        ? (DateTime?)Convert.ToDateTime(dr["ExpiraEm"])
                        : null
                };
            }

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

            return modelo;
        }

    }
}
