-- Migration: 001_business_context_tables.sql
-- Description: Add business context questions and responses tables to requirement processor
-- Date: 2024-01-15

-- Business Context Responses (Simple Structure)
CREATE TABLE IF NOT EXISTS business_context_responses (
    id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
    user_id UUID NOT NULL,
    template_id UUID,
    project_id UUID,
    
    -- Simple JSONB structure with questions array
    questions JSONB NOT NULL DEFAULT '[]'::jsonb,
    
    -- Metadata
    status VARCHAR(50) DEFAULT 'in_progress',
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    
    CONSTRAINT valid_status CHECK (status IN ('in_progress', 'completed', 'draft'))
);

-- Question Templates (Optional - for reusable question sets)
CREATE TABLE IF NOT EXISTS question_templates (
    id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
    template_name VARCHAR(255) NOT NULL,
    questions JSONB NOT NULL DEFAULT '[]'::jsonb,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    is_active BOOLEAN DEFAULT true
);

-- Create indexes
CREATE INDEX IF NOT EXISTS idx_business_context_user_id ON business_context_responses(user_id);
CREATE INDEX IF NOT EXISTS idx_business_context_project_id ON business_context_responses(project_id);
CREATE INDEX IF NOT EXISTS idx_business_context_template_id ON business_context_responses(template_id);
CREATE INDEX IF NOT EXISTS idx_business_context_questions ON business_context_responses USING GIN (questions);
CREATE INDEX IF NOT EXISTS idx_question_templates_questions ON question_templates USING GIN (questions);

-- Insert default question template
INSERT INTO question_templates (template_name, questions) VALUES 
('Standard Business Context Questions', '[
    {
        "question": "How many local users will access your integrated restaurant Management System system across all detailed requirements?",
        "answer": ""
    },
    {
        "question": "How should Customer-Facing Features, Management Dashboard, Staff Operations interface features with their detailed requirements integrate and share data?",
        "answer": ""
    },
    {
        "question": "What are the workflow dependencies between detailed requirements?",
        "answer": ""
    },
    {
        "question": "Do you need real-time data synchronization across all detailed requirements?",
        "answer": ""
    },
    {
        "question": "How should data flow between these detailed requirements?",
        "answer": ""
    }
]'::jsonb)
ON CONFLICT DO NOTHING;
