-- 환자 사전 문진표 시스템 테이블

-- 1. 문진 메인 테이블
CREATE TABLE IF NOT EXISTS patient_surveys (
    survey_id INTEGER PRIMARY KEY AUTOINCREMENT,
    patient_id INTEGER,
    survey_token TEXT UNIQUE NOT NULL,  -- QR/링크용 고유 토큰
    survey_date DATE DEFAULT (date('now')),
    status TEXT DEFAULT 'PENDING' CHECK(status IN ('PENDING', 'IN_PROGRESS', 'COMPLETED', 'REVIEWED')),
    created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    completed_at DATETIME,
    reviewed_at DATETIME,
    reviewed_by TEXT,
    notes TEXT,
    FOREIGN KEY (patient_id) REFERENCES patients(patient_id)
);

CREATE INDEX IF NOT EXISTS idx_survey_token ON patient_surveys(survey_token);
CREATE INDEX IF NOT EXISTS idx_survey_patient ON patient_surveys(patient_id);

-- 2. 문진 응답 테이블
CREATE TABLE IF NOT EXISTS survey_responses (
    response_id INTEGER PRIMARY KEY AUTOINCREMENT,
    survey_id INTEGER NOT NULL,
    category TEXT NOT NULL,  -- 카테고리 (TEMPERATURE, BODY_TEMP, DIGESTION, etc)
    question_code TEXT NOT NULL,  -- 질문 코드
    question_text TEXT,  -- 질문 내용
    answer_value TEXT,  -- 응답 값 (JSON 또는 TEXT)
    answer_type TEXT,  -- SINGLE, MULTIPLE, TEXT, RANGE
    created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    FOREIGN KEY (survey_id) REFERENCES patient_surveys(survey_id) ON DELETE CASCADE
);

CREATE INDEX IF NOT EXISTS idx_response_survey ON survey_responses(survey_id);
CREATE INDEX IF NOT EXISTS idx_response_category ON survey_responses(category);

-- 3. 문진 템플릿 테이블 (질문 정의)
CREATE TABLE IF NOT EXISTS survey_templates (
    template_id INTEGER PRIMARY KEY AUTOINCREMENT,
    category TEXT NOT NULL,
    category_name TEXT NOT NULL,  -- 카테고리 한글명
    question_code TEXT NOT NULL UNIQUE,
    question_text TEXT NOT NULL,
    question_subtext TEXT,  -- 부가 설명
    input_type TEXT NOT NULL CHECK(input_type IN ('RADIO', 'CHECKBOX', 'RANGE', 'TEXT', 'TEXTAREA', 'NUMBER')),
    options TEXT,  -- JSON 배열 형태의 선택지
    is_required INTEGER DEFAULT 1,
    sort_order INTEGER DEFAULT 0,
    is_active INTEGER DEFAULT 1,
    created_at DATETIME DEFAULT CURRENT_TIMESTAMP
);

CREATE INDEX IF NOT EXISTS idx_template_category ON survey_templates(category);
CREATE INDEX IF NOT EXISTS idx_template_active ON survey_templates(is_active);

-- 4. 문진 진행 상태 추적 테이블
CREATE TABLE IF NOT EXISTS survey_progress (
    progress_id INTEGER PRIMARY KEY AUTOINCREMENT,
    survey_id INTEGER NOT NULL,
    category TEXT NOT NULL,
    total_questions INTEGER DEFAULT 0,
    answered_questions INTEGER DEFAULT 0,
    is_completed INTEGER DEFAULT 0,
    last_updated DATETIME DEFAULT CURRENT_TIMESTAMP,
    FOREIGN KEY (survey_id) REFERENCES patient_surveys(survey_id) ON DELETE CASCADE,
    UNIQUE(survey_id, category)
);

CREATE INDEX IF NOT EXISTS idx_progress_survey ON survey_progress(survey_id);
