package tests

import (
	"testing"

	"nex/backend/internal/config"

	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"
)

func TestMigration_ModelsUUIDPrimaryKey(t *testing.T) {
	db := SetupTestDB(t)
	defer CleanupTestDB(t, db)

	// 创建供应商
	_ = CreateTestProvider(t, db, "openai")

	// 创建模型使用 UUID 作为 id
	model, err := CreateTestModel(t, db, "550e8400-e29b-41d4-a716-446655440000", "openai", "gpt-4")
	require.NoError(t, err)

	// 通过 UUID 查询
	var result config.Model
	require.NoError(t, db.First(&result, "id = ?", model.ID).Error)
	assert.Equal(t, "gpt-4", result.ModelName)
}

func TestMigration_UniqueProviderModelConstraint(t *testing.T) {
	db := SetupTestDB(t)
	defer CleanupTestDB(t, db)

	// 创建供应商
	_ = CreateTestProvider(t, db, "openai")

	// 创建第一个模型
	_, err := CreateTestModel(t, db, "uuid-1", "openai", "gpt-4")
	require.NoError(t, err)

	// 尝试创建相同 (provider_id, model_name) 的模型应失败
	_, err = CreateTestModel(t, db, "uuid-2", "openai", "gpt-4")
	assert.Error(t, err, "UNIQUE(provider_id, model_name) 约束应阻止重复")

	// 不同 provider_id 下相同 model_name 应成功
	_ = CreateTestProvider(t, db, "anthropic")
	_, err = CreateTestModel(t, db, "uuid-3", "anthropic", "gpt-4")
	require.NoError(t, err, "不同 provider_id 下相同 model_name 应允许")
}

func TestMigration_CascadeDelete(t *testing.T) {
	db := SetupTestDB(t)
	defer CleanupTestDB(t, db)

	// 创建供应商和模型
	provider := CreateTestProvider(t, db, "openai")
	_, err := CreateTestModel(t, db, "uuid-1", "openai", "gpt-4")
	require.NoError(t, err)

	// 删除供应商应级联删除模型
	require.NoError(t, db.Delete(&provider).Error)

	var count int64
	db.Model(&config.Model{}).Where("provider_id = ?", "openai").Count(&count)
	assert.Equal(t, int64(0), count, "删除供应商后其模型应被级联删除")
}

func TestMigration_ModelDefaultEnabled(t *testing.T) {
	db := SetupTestDB(t)
	defer CleanupTestDB(t, db)

	_ = CreateTestProvider(t, db, "openai")

	// 创建模型不指定 enabled，应默认为 true
	_, err := CreateTestModel(t, db, "uuid-1", "openai", "gpt-4")
	require.NoError(t, err)

	var result config.Model
	require.NoError(t, db.First(&result, "id = ?", "uuid-1").Error)
	assert.True(t, result.Enabled, "enabled 字段默认应为 true")
}
