-- 数据库层测试脚本
-- 用法: psql -h demo/db/socket -p 5434 -d wxchat_sales -f test_db.sql

-- 测试1: 验证 6 张表存在
\echo '=== TEST 1: 表存在性检查 ==='
SELECT tablename FROM pg_tables WHERE schemaname='public' ORDER BY tablename;
-- 预期: contact, conversation, customer, deal, message, salesperson

-- 测试2: 验证 3 名预置销售
\echo '=== TEST 2: 销售人员数据 ==='
SELECT id, name, team, wx_account FROM salesperson ORDER BY id;
-- 预期: 3 行

-- 测试3: 验证唯一约束（插入重复销售应跳过）
\echo '=== TEST 3: 幂等插入 ==='
INSERT INTO salesperson (id, name, team, wx_account, device_id) VALUES
    (1, '张伟', '华东团队', 'wxid_zhangwei', 'macbook-zw-001')
ON CONFLICT (id) DO NOTHING;
SELECT count(*) AS salesperson_count FROM salesperson;
-- 预期: 3

-- 测试4: 验证 contact 唯一约束
\echo '=== TEST 4: contact 唯一约束 ==='
INSERT INTO contact (salesperson_id, wx_username, display_name) VALUES (1, 'test_dup', '测试');
-- 第二次插入应失败
DO $$
BEGIN
    INSERT INTO contact (salesperson_id, wx_username, display_name) VALUES (1, 'test_dup', '测试2');
    RAISE EXCEPTION '唯一约束未生效';
EXCEPTION
    WHEN unique_violation THEN
        RAISE NOTICE '唯一约束生效: OK';
END $$;
-- 清理
DELETE FROM contact WHERE wx_username = 'test_dup';

-- 测试5: 验证外键约束
\echo '=== TEST 5: 外键约束 ==='
DO $$
BEGIN
    INSERT INTO contact (salesperson_id, wx_username, display_name) VALUES (999, 'test_fk', '测试');
    RAISE EXCEPTION '外键约束未生效';
EXCEPTION
    WHEN foreign_key_violation THEN
        RAISE NOTICE '外键约束生效: OK';
END $$;

-- 测试6: 验证索引存在
\echo '=== TEST 6: 索引检查 ==='
SELECT indexname FROM pg_indexes WHERE schemaname='public' ORDER BY indexname;

\echo '=== ALL TESTS DONE ==='
