using System;
using Dapper;
using MySqlConnector;

namespace CncRepository.Tests
{
    /// <summary>
    /// 测试数据库连接辅助类
    /// 所有测试共享 cnc_test 库，每条测试后清理数据
    /// 使用 DELETE FROM 代替 TRUNCATE，避免外键约束阻止DDL操作
    /// </summary>
    public static class TestDb
    {
        /// <summary>测试库连接串</summary>
        public static readonly string ConnectionString =
            "Server=localhost;Database=cnc_test;Uid=root;Pwd=root;Charset=utf8mb4;SslMode=None;";

        /// <summary>
        /// 清空所有测试表（按外键依赖倒序DELETE，然后重置自增）
        /// </summary>
        public static void TruncateAll()
        {
            using (var conn = new MySqlConnection(ConnectionString))
            {
                // 按外键依赖倒序：先删子表，再删父表
                var tables = new[]
                {
                    "cnc_worker_machine",
                    "cnc_production_segment",
                    "cnc_machine_daily_status",
                    "cnc_worker_daily_summary",
                    "cnc_daily_production",
                    "cnc_production_adjustment",
                    "cnc_alert",
                    "cnc_machine",
                    "cnc_collect_address",
                    "cnc_brand_field_mapping",
                    "cnc_screen_filter",
                    "cnc_screen_config",
                    "cnc_worker",
                    "cnc_sys_config",
                    "cnc_workshop",
                    "cnc_brand"
                };

                // 禁用外键检查以允许DELETE和重置AUTO_INCREMENT
                conn.Execute("SET FOREIGN_KEY_CHECKS = 0");
                foreach (var table in tables)
                {
                    conn.Execute($"DELETE FROM {table}");
                    conn.Execute($"ALTER TABLE {table} AUTO_INCREMENT = 1");
                }
                conn.Execute("SET FOREIGN_KEY_CHECKS = 1");
            }

            // 重新插入种子数据
            SeedData();
        }

        /// <summary>
        /// 插入基础种子数据
        /// </summary>
        public static void SeedData()
        {
            using (var conn = new MySqlConnection(ConnectionString))
            {
                // 品牌
                conn.Execute(@"INSERT IGNORE INTO cnc_brand (id, brand_name, device_field, tags_path, is_enabled, created_at, updated_at)
                    VALUES (1, 'FANUC', 'device', 'tags', 1, NOW(), NOW())");

                // 车间
                conn.Execute(@"INSERT IGNORE INTO cnc_workshop (id, name, sort_order, is_enabled, created_at, updated_at)
                    VALUES (1, 'A栋', 1, 1, NOW(), NOW()), (2, 'B栋', 2, 1, NOW(), NOW())");

                // 系统配置（admin账号）
                conn.Execute(@"INSERT IGNORE INTO cnc_sys_config (config_key, config_value, value_type, description, updated_at)
                    VALUES ('admin_username', 'admin', 'string', '管理员用户名', NOW()),
                           ('admin_password_hash', '$2a$11$dummyhashfortesting', 'string', '管理员密码哈希', NOW())");
            }
        }

        /// <summary>
        /// 执行SQL并返回受影响行数
        /// </summary>
        public static int Execute(string sql, object param = null)
        {
            using (var conn = new MySqlConnection(ConnectionString))
            {
                return conn.Execute(sql, param);
            }
        }

        /// <summary>
        /// 查询单个值
        /// </summary>
        public static T QuerySingle<T>(string sql, object param = null)
        {
            using (var conn = new MySqlConnection(ConnectionString))
            {
                return conn.QuerySingle<T>(sql, param);
            }
        }
    }
}
