using System.Collections.Generic;
using System.Linq;
using Dapper;
using CncModels.Entity;
using CncRepository.Base;
using CncRepository.Interface;
using System.Data;

namespace CncRepository.Impl
{
    /// <summary>
    /// 系统配置实现
    /// </summary>
    public class SysConfigRepository : BusinessRepository, ISysConfigRepository
    {
        public SysConfigRepository(string connectionString) : base(connectionString) { }

        /// <inheritdoc/>
        public SysConfig GetByKey(string configKey)
        {
            using (var conn = CreateConnection())
            {
                var sql = @"SELECT id as Id, config_key as ConfigKey, config_value as ConfigValue, value_type as ValueType, description as Description, updated_at as UpdatedAt 
                            FROM cnc_sys_config WHERE config_key = @ConfigKey LIMIT 1";
                return conn.QuerySingleOrDefault<SysConfig>(sql, new { ConfigKey = configKey });
            }
        }

        /// <inheritdoc/>
        public List<SysConfig> GetAll()
        {
            using (var conn = CreateConnection())
            {
                var sql = @"SELECT id as Id, config_key as ConfigKey, config_value as ConfigValue, value_type as ValueType, description as Description, updated_at as UpdatedAt FROM cnc_sys_config ORDER BY id";
                return conn.Query<SysConfig>(sql).ToList();
            }
        }

        /// <inheritdoc/>
        public bool UpdateValue(int id, string configValue)
        {
            using (var conn = CreateConnection())
            {
                var sql = @"UPDATE cnc_sys_config SET config_value = @ConfigValue, updated_at = NOW() WHERE id = @Id";
                var affected = conn.Execute(sql, new { Id = id, ConfigValue = configValue });
                return affected > 0;
            }
        }
    }
}
