-- Use-Case Compiler: Audits + Answers
-- Turns Master Controls into interactive questionnaires

CREATE TABLE IF NOT EXISTS compliance.usecase_audits (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    tenant_id UUID NOT NULL,
    template_id VARCHAR(100) NOT NULL,
    name VARCHAR(200) NOT NULL,
    target_name VARCHAR(200),
    status VARCHAR(20) DEFAULT 'draft',
    total_questions INT DEFAULT 0,
    answered_questions INT DEFAULT 0,
    compliance_score FLOAT DEFAULT 0,
    questions JSONB DEFAULT '[]',
    created_at TIMESTAMPTZ DEFAULT NOW(),
    updated_at TIMESTAMPTZ DEFAULT NOW(),
    completed_at TIMESTAMPTZ
);

CREATE INDEX IF NOT EXISTS idx_usecase_audits_tenant
    ON compliance.usecase_audits (tenant_id);
CREATE INDEX IF NOT EXISTS idx_usecase_audits_template
    ON compliance.usecase_audits (template_id);

CREATE TABLE IF NOT EXISTS compliance.usecase_answers (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    audit_id UUID NOT NULL REFERENCES compliance.usecase_audits(id) ON DELETE CASCADE,
    question_id VARCHAR(50) NOT NULL,
    mc_id VARCHAR(50),
    answer JSONB NOT NULL,
    evidence_ids JSONB DEFAULT '[]',
    status VARCHAR(20) DEFAULT 'answered',
    answered_at TIMESTAMPTZ DEFAULT NOW()
);

CREATE INDEX IF NOT EXISTS idx_usecase_answers_audit
    ON compliance.usecase_answers (audit_id);
CREATE UNIQUE INDEX IF NOT EXISTS idx_usecase_answers_unique
    ON compliance.usecase_answers (audit_id, question_id);
