-- AI Mockup Service Database Schema
-- This service only creates wireframe-related tables
-- User authentication tables are managed by user-auth service

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

-- Wireframes table - Store wireframe data
CREATE TABLE IF NOT EXISTS wireframes (
  id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
  user_id UUID NOT NULL, -- References users table from user-auth service
  project_id UUID, -- References projects table from core schema
  title VARCHAR(255) NOT NULL,
  description TEXT,
  wireframe_data JSONB NOT NULL, -- Store the actual wireframe JSON
  thumbnail_url VARCHAR(500),
  status VARCHAR(50) DEFAULT 'draft',
  created_at TIMESTAMP DEFAULT NOW(),
  updated_at TIMESTAMP DEFAULT NOW()
);

-- Wireframe versions table - Track different versions of wireframes
CREATE TABLE IF NOT EXISTS wireframe_versions (
  id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
  wireframe_id UUID REFERENCES wireframes(id) ON DELETE CASCADE,
  version_number INTEGER NOT NULL,
  wireframe_data JSONB NOT NULL,
  change_description TEXT,
  created_at TIMESTAMP DEFAULT NOW(),
  UNIQUE(wireframe_id, version_number)
);

-- Wireframe elements table - Store individual elements for analysis
CREATE TABLE IF NOT EXISTS wireframe_elements (
  id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
  wireframe_id UUID REFERENCES wireframes(id) ON DELETE CASCADE,
  element_type VARCHAR(100) NOT NULL, -- button, input, text, image, etc.
  element_data JSONB NOT NULL,
  position_x INTEGER,
  position_y INTEGER,
  width INTEGER,
  height INTEGER,
  created_at TIMESTAMP DEFAULT NOW()
);

-- Indexes for performance
CREATE INDEX IF NOT EXISTS idx_wireframes_user_id ON wireframes(user_id);
CREATE INDEX IF NOT EXISTS idx_wireframes_project_id ON wireframes(project_id);
CREATE INDEX IF NOT EXISTS idx_wireframes_status ON wireframes(status);
CREATE INDEX IF NOT EXISTS idx_wireframe_versions_wireframe_id ON wireframe_versions(wireframe_id);
CREATE INDEX IF NOT EXISTS idx_wireframe_elements_wireframe_id ON wireframe_elements(wireframe_id);
CREATE INDEX IF NOT EXISTS idx_wireframe_elements_type ON wireframe_elements(element_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_wireframes_updated_at 
  BEFORE UPDATE ON wireframes
  FOR EACH ROW EXECUTE FUNCTION update_updated_at_column();

-- Success message
SELECT 'AI Mockup Service database schema created successfully!' as message;

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