using System;
using System.Data;
using MySqlConnector;

namespace CncRepository.Base
{
    /// <summary>
    /// 仓储基类，提供数据库连接管理
    /// 每个仓储方法应 using(CreateConnection()) 自动释放连接
    /// </summary>
    public abstract class BaseRepository
    {
        private readonly string _connectionString;

        /// <summary>
        /// 初始化仓储基类
        /// </summary>
        /// <param name="connectionString">数据库连接字符串</param>
        protected BaseRepository(string connectionString)
        {
            _connectionString = connectionString ?? throw new ArgumentNullException(nameof(connectionString));
        }

        /// <summary>
        /// 创建新的数据库连接
        /// 调用方需使用 using 语句确保连接释放
        /// </summary>
        /// <example>
        /// using (var conn = CreateConnection())
        /// {
        ///     return conn.QueryFirstOrDefault&lt;Machine&gt;("SELECT * FROM cnc_machine WHERE id = @Id", new { Id = id });
        /// }
        /// </example>
        protected IDbConnection CreateConnection()
        {
            return new MySqlConnection(_connectionString);
        }
    }
}
