-- Tech Stack Selector Database Schema
-- Minimal schema for tech stack recommendations only

-- Enable UUID extension if not already enabled
CREATE EXTENSION IF NOT EXISTS "uuid-ossp";

-- Tech stack recommendations table - Store AI-generated recommendations
CREATE TABLE IF NOT EXISTS tech_stack_recommendations (
  id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
  project_id UUID REFERENCES projects(id) ON DELETE CASCADE,
  user_requirements TEXT NOT NULL,
  recommended_stack JSONB NOT NULL, -- Store the complete tech stack recommendation
  confidence_score DECIMAL(3,2) CHECK (confidence_score >= 0.0 AND confidence_score <= 1.0),
  reasoning TEXT,
  created_at TIMESTAMP DEFAULT NOW(),
  updated_at TIMESTAMP DEFAULT NOW()
);

-- Stack analysis cache - Cache AI analysis results
CREATE TABLE IF NOT EXISTS stack_analysis_cache (
  id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
  requirements_hash VARCHAR(64) UNIQUE NOT NULL, -- Hash of requirements for cache key
  project_type VARCHAR(100),
  analysis_result JSONB NOT NULL,
  confidence_score DECIMAL(3,2),
  created_at TIMESTAMP DEFAULT NOW()
);

-- Indexes for performance
CREATE INDEX IF NOT EXISTS idx_tech_stack_recommendations_project_id ON tech_stack_recommendations(project_id);
CREATE INDEX IF NOT EXISTS idx_tech_stack_recommendations_created_at ON tech_stack_recommendations(created_at);
CREATE INDEX IF NOT EXISTS idx_stack_analysis_cache_hash ON stack_analysis_cache(requirements_hash);
CREATE INDEX IF NOT EXISTS idx_stack_analysis_cache_project_type ON stack_analysis_cache(project_type);

-- Update timestamps trigger function
CREATE OR REPLACE FUNCTION update_updated_at_column()
RETURNS TRIGGER AS $$
BEGIN
    NEW.updated_at = NOW();
    RETURN NEW;
END;
$$ language 'plpgsql';

-- Apply triggers for updated_at columns
CREATE TRIGGER update_tech_stack_recommendations_updated_at 
  BEFORE UPDATE ON tech_stack_recommendations
  FOR EACH ROW EXECUTE FUNCTION update_updated_at_column();

-- Success message
SELECT 'Tech Stack Selector database schema created successfully!' as message;

-- Display created tables
SELECT 
  schemaname,
  tablename,
  tableowner
FROM pg_tables 
WHERE schemaname = 'public' 
AND tablename IN ('tech_stack_recommendations', 'stack_analysis_cache')
ORDER BY tablename;
