package com.chick_mood.data.database

import android.content.Context
import android.util.Log
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import com.chick_mood.data.model.Emotion
import com.chick_mood.data.model.UserConfigEntry

/**
 * 数据库测试辅助类
 *
 * 用于在应用启动时测试数据库功能
 * 验证基本的CRUD操作是否正常工作
 *
 * @author Claude
 * @date 2025-10-22
 */
class DatabaseTestHelper private constructor() {

    companion object {
        private const val TAG = "DatabaseTestHelper"

        /**
         * 在应用启动时运行数据库测试
         */
        fun runDatabaseTests(context: Context) {
            CoroutineScope(Dispatchers.IO).launch {
                try {
                    Log.d(TAG, "开始数据库测试...")

                    val dbManager = SimpleDatabaseManager.getInstance(context)

                    // 测试1: 创建心情记录
                    testCreateMoodRecord(dbManager)

                    // 测试2: 查询心情记录
                    testQueryMoodRecords(dbManager)

                    // 测试3: 用户配置操作
                    testUserConfig(dbManager)

                    // 测试4: 初始化默认配置
                    testInitializeDefaultConfig(dbManager)

                    Log.d(TAG, "所有数据库测试完成！")

                } catch (e: Exception) {
                    Log.e(TAG, "数据库测试失败", e)
                }
            }
        }

        /**
         * 测试创建心情记录
         */
        private suspend fun testCreateMoodRecord(dbManager: SimpleDatabaseManager) {
            Log.d(TAG, "测试创建心情记录...")

            val recordId = dbManager.createMoodRecord(
                emotion = Emotion.HAPPY,
                intensity = 85,
                noteText = "数据库测试记录",
                imagePaths = emptyList()
            )

            Log.d(TAG, "创建的心情记录ID: $recordId")
            assertTrue("记录ID应该大于0", recordId > 0)
        }

        /**
         * 测试查询心情记录
         */
        private suspend fun testQueryMoodRecords(dbManager: SimpleDatabaseManager) {
            Log.d(TAG, "测试查询心情记录...")

            val recentRecords = dbManager.getRecentMoodRecords(5)
            Log.d(TAG, "查询到 ${recentRecords.size} 条最近记录")

            val totalCount = dbManager.getMoodRecordCount()
            Log.d(TAG, "心情记录总数: $totalCount")

            assertTrue("记录数应该大于等于0", totalCount >= 0)
        }

        /**
         * 测试用户配置操作
         */
        private suspend fun testUserConfig(dbManager: SimpleDatabaseManager) {
            Log.d(TAG, "测试用户配置操作...")

            // 设置测试昵称
            dbManager.setUserNickname("数据库测试用户")
            val nickname = dbManager.getUserNickname()
            Log.d(TAG, "用户昵称: $nickname")
            assertEquals("昵称应该正确", "数据库测试用户", nickname)

            // 设置测试配置
            dbManager.setConfigValue("test_key", "test_value")
            val value = dbManager.getConfigValue("test_key")
            Log.d(TAG, "测试配置值: $value")
            assertEquals("配置值应该正确", "test_value", value)
        }

        /**
         * 测试初始化默认配置
         */
        private suspend fun testInitializeDefaultConfig(dbManager: SimpleDatabaseManager) {
            Log.d(TAG, "测试初始化默认配置...")

            dbManager.initializeDefaultConfig()

            // 验证默认配置是否设置成功
            val nickname = dbManager.getUserNickname()
            Log.d(TAG, "默认昵称: $nickname")
            assertNotNull("应该有默认昵称", nickname)

            val version = dbManager.getConfigValue(UserConfigEntry.KEY_APP_VERSION)
            Log.d(TAG, "应用版本: $version")
            assertNotNull("应该有版本信息", version)

            val soundEnabled = dbManager.getConfigValue(UserConfigEntry.KEY_SOUND_ENABLED)
            Log.d(TAG, "声音开关: $soundEnabled")
            assertNotNull("应该有声音开关设置", soundEnabled)
        }

        /**
         * 简单的断言方法
         */
        private fun assertTrue(message: String, condition: Boolean) {
            if (condition) {
                Log.d(TAG, "✅ $message")
            } else {
                Log.e(TAG, "❌ $message")
            }
        }

        private fun assertEquals(message: String, expected: String?, actual: String?) {
            if (expected == actual) {
                Log.d(TAG, "✅ $message - 期望: $expected, 实际: $actual")
            } else {
                Log.e(TAG, "❌ $message - 期望: $expected, 实际: $actual")
            }
        }

        private fun assertNotNull(message: String, value: Any?) {
            if (value != null) {
                Log.d(TAG, "✅ $message - 值: $value")
            } else {
                Log.e(TAG, "❌ $message - 值为null")
            }
        }
    }
}