-- 诊疗记录系统数据库表
-- 包含医生诊疗记录及紧急程度评估

-- 先删除旧表以确保重新部署
DROP TABLE IF EXISTS public.ec_doctor_consultations CASCADE;

-- 创建诊疗记录表
CREATE TABLE public.ec_doctor_consultations (
    id SERIAL PRIMARY KEY,
    patient_name VARCHAR(100) NOT NULL,
    consultation_date DATE NOT NULL DEFAULT CURRENT_DATE,
    diagnosis TEXT NOT NULL,
    urgency VARCHAR(20) NOT NULL DEFAULT 'normal', -- urgency: emergency, urgent, normal
    doctor_id UUID, -- 可选：关联医生ID
    created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP
);

-- 添加字段注释
COMMENT ON COLUMN public.ec_doctor_consultations.urgency IS '紧急程度: emergency (红色), urgent (橙色), normal (普通)';

-- 插入初始化测试数据
INSERT INTO public.ec_doctor_consultations (patient_name, consultation_date, diagnosis, urgency)
VALUES 
('张三', '2024-01-15', '感冒，发热，建议休息多喝水', 'normal'),
('李四', '2024-01-14', '高血压，建议定期检查', 'urgent'),
('王五', '2024-01-16', '急性胸痛，疑心肌梗死，需紧急处置', 'emergency');

-- 创建常用查询索引
CREATE INDEX IF NOT EXISTS idx_consultation_patient_name ON public.ec_doctor_consultations(patient_name);
CREATE INDEX IF NOT EXISTS idx_consultation_date ON public.ec_doctor_consultations(consultation_date);
CREATE INDEX IF NOT EXISTS idx_consultation_urgency ON public.ec_doctor_consultations(urgency);

-- 启用行级安全 (RLS)
ALTER TABLE public.ec_doctor_consultations ENABLE ROW LEVEL SECURITY;

-- 创建基本的安全策略 (允许所有认证用户读取，实际生产应根据角色细分)
DROP POLICY IF EXISTS "允许认证用户查看诊疗记录" ON public.ec_doctor_consultations;
CREATE POLICY "允许认证用户查看诊疗记录" ON public.ec_doctor_consultations
    FOR SELECT 
    TO authenticated
    USING (true);

-- 即使在本地预览模式下，也允许匿名访问（仅限测试）
DROP POLICY IF EXISTS "允许匿名查询测试数据" ON public.ec_doctor_consultations;
CREATE POLICY "允许匿名查询测试数据" ON public.ec_doctor_consultations
    FOR SELECT 
    TO anon
    USING (true);
