-- ON CONFLICT 修复验证脚本
-- 此脚本用于验证所有ON CONFLICT语句是否能正确执行

-- 1. 测试 ak_content_categories 的 name_key 唯一约束
INSERT INTO public.ak_content_categories (name_key, ai_keywords, sort_order) 
VALUES ('test.conflict.category', ARRAY['测试冲突'], 999)
ON CONFLICT (name_key) DO NOTHING;

-- 再次插入相同的name_key，应该被忽略
INSERT INTO public.ak_content_categories (name_key, ai_keywords, sort_order) 
VALUES ('test.conflict.category', ARRAY['测试冲突重复'], 1000)
ON CONFLICT (name_key) DO NOTHING;

-- 2. 测试 ak_ai_usage_stats 的复合唯一约束
INSERT INTO public.ak_ai_usage_stats (
    service_type, ai_provider, date_bucket, tokens_used, requests_count, 
    cost_usd, processing_time_ms, success_count, error_count
) VALUES (
    'test_service', 'test_provider', CURRENT_DATE, 100, 1, 0.01, 500, 1, 0
)
ON CONFLICT (service_type, ai_provider, date_bucket) 
DO UPDATE SET
    tokens_used = ak_ai_usage_stats.tokens_used + EXCLUDED.tokens_used,
    requests_count = ak_ai_usage_stats.requests_count + 1,
    cost_usd = ak_ai_usage_stats.cost_usd + EXCLUDED.cost_usd;

-- 3. 测试 ak_database_versions 的 version 唯一约束
INSERT INTO public.ak_database_versions (version, description) 
VALUES ('test.version.1.0', '测试版本冲突处理')
ON CONFLICT (version) DO NOTHING;

-- 再次插入相同版本，应该被忽略
INSERT INTO public.ak_database_versions (version, description) 
VALUES ('test.version.1.0', '测试版本冲突处理 - 重复')
ON CONFLICT (version) DO NOTHING;

-- 验证结果
SELECT count(*) as category_test_count FROM public.ak_content_categories WHERE name_key = 'test.conflict.category';
SELECT count(*) as stats_test_count FROM public.ak_ai_usage_stats WHERE service_type = 'test_service' AND ai_provider = 'test_provider';
SELECT count(*) as version_test_count FROM public.ak_database_versions WHERE version = 'test.version.1.0';

-- 清理测试数据
DELETE FROM public.ak_content_categories WHERE name_key = 'test.conflict.category';
DELETE FROM public.ak_ai_usage_stats WHERE service_type = 'test_service' AND ai_provider = 'test_provider';
DELETE FROM public.ak_database_versions WHERE version = 'test.version.1.0';
