using System;
using System.Data;
using MySqlConnector;

namespace Karaoke_Kingpin.Models
{
    public class MyDB : IDisposable
    {
        private readonly string connectionString = "Server=192.168.22.170;Port=3306;Database=Karaoke-Kingpin;User=Karaoke-Kingpin;Password=ESM7yTPMnavFmbBH;";
        private MySqlConnection conn;

        public MyDB()
        {
            conn = new MySqlConnection(connectionString);
            conn.Open();
            Console.WriteLine("MyDB 連線成功！");
        }

        public void Dispose()
        {
            if (conn != null)
            {
                conn.Close();
                Console.WriteLine("MyDB 連線已關閉！");
            }
        }

        // SELECT 方法
        public DataTable Select(string query, MySqlParameter[] parameters)
        {
            using (var cmd = new MySqlCommand(query, conn))
            {
                if (parameters != null)
                {
                    cmd.Parameters.AddRange(parameters);
                }
                using (var adapter = new MySqlDataAdapter(cmd))
                {
                    DataTable result = new DataTable();
                    adapter.Fill(result);
                    return result;
                }
            }
        }

        // INSERT / UPDATE / DELETE 方法
        public int ExecuteNonQuery(string query, MySqlParameter[] parameters)
        {
            using (var cmd = new MySqlCommand(query, conn))
            {
                if (parameters != null)
                {
                    cmd.Parameters.AddRange(parameters);
                }
                return cmd.ExecuteNonQuery();
            }
        }
    }
}
