-- Smilegate customer Excel QA benchmark history.
-- This script is also applied by poc4_active_source_20260714/scripts/
-- sync_smilegate_qa_history.py with existence checks for repeatable deployment.

CREATE TABLE SG_AI_QA_QUESTION (
    question_id NUMBER GENERATED BY DEFAULT ON NULL AS IDENTITY PRIMARY KEY,
    question_code VARCHAR2(30) UNIQUE,
    question_source VARCHAR2(30) NOT NULL,
    question_hash VARCHAR2(64) NOT NULL UNIQUE,
    category VARCHAR2(30) NOT NULL,
    title VARCHAR2(200) NOT NULL,
    question_text CLOB NOT NULL,
    source_document VARCHAR2(255),
    source_sheet VARCHAR2(255),
    source_row NUMBER,
    source_scenario CLOB,
    sample_sql CLOB,
    expected_focus CLOB,
    baseline_sql CLOB,
    baseline_answer CLOB,
    support_level VARCHAR2(20) NOT NULL,
    evaluation_rule_json CLOB CHECK (evaluation_rule_json IS JSON),
    active_yn CHAR(1) DEFAULT 'Y' NOT NULL CHECK (active_yn IN ('Y', 'N')),
    created_at TIMESTAMP WITH TIME ZONE DEFAULT SYSTIMESTAMP NOT NULL,
    updated_at TIMESTAMP WITH TIME ZONE DEFAULT SYSTIMESTAMP NOT NULL,
    CONSTRAINT sg_ai_qa_question_source_ck
        CHECK (question_source IN ('CUSTOMER_EXCEL', 'FREE_TEXT'))
);

CREATE TABLE SG_AI_QA_ANSWER (
    answer_seq NUMBER GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    question_id NUMBER NOT NULL,
    answer_kind VARCHAR2(20) NOT NULL,
    run_key VARCHAR2(100),
    conversation_id VARCHAR2(100),
    requested_by VARCHAR2(100),
    requested_at TIMESTAMP WITH TIME ZONE DEFAULT SYSTIMESTAMP NOT NULL,
    model_profile VARCHAR2(100),
    generated_sql CLOB,
    answer_text CLOB,
    result_json CLOB CHECK (result_json IS JSON),
    execution_output CLOB,
    execution_status VARCHAR2(40),
    judgment_status VARCHAR2(20) NOT NULL,
    judgment_reason CLOB,
    duration_ms NUMBER,
    created_at TIMESTAMP WITH TIME ZONE DEFAULT SYSTIMESTAMP NOT NULL,
    CONSTRAINT sg_ai_qa_answer_question_fk
        FOREIGN KEY (question_id)
        REFERENCES SG_AI_QA_QUESTION (question_id)
        ON DELETE CASCADE,
    CONSTRAINT sg_ai_qa_answer_kind_ck
        CHECK (answer_kind IN ('HISTORICAL', 'LIVE')),
    CONSTRAINT sg_ai_qa_answer_judgment_ck
        CHECK (judgment_status IN ('PASS', 'WARN', 'FAIL', 'REVIEW'))
);

CREATE INDEX sg_ai_qa_answer_question_ix
    ON SG_AI_QA_ANSWER (question_id, answer_seq DESC);

CREATE UNIQUE INDEX sg_ai_qa_answer_run_uk
    ON SG_AI_QA_ANSWER (question_id, run_key);
