-- Create UUID extension
CREATE EXTENSION IF NOT EXISTS "uuid-ossp";

-- Create functions table
CREATE TABLE functions (
    id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
    name VARCHAR(255) NOT NULL,
    app_id VARCHAR(255) NOT NULL,
    runtime VARCHAR(50) NOT NULL,
    image VARCHAR(500) NOT NULL,
    handler VARCHAR(255) NOT NULL,
    code TEXT,
    environment JSONB DEFAULT '{}',
    timeout INTERVAL NOT NULL DEFAULT '30 seconds',
    memory INTEGER NOT NULL DEFAULT 128,
    owner_type VARCHAR(50) NOT NULL,
    owner_name VARCHAR(255) NOT NULL,
    owner_owner VARCHAR(255) NOT NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    
    UNIQUE(app_id, name)
);

-- Create executions table
CREATE TABLE executions (
    id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
    function_id UUID NOT NULL REFERENCES functions(id) ON DELETE CASCADE,
    status VARCHAR(50) NOT NULL DEFAULT 'pending',
    input JSONB,
    output JSONB,
    error TEXT,
    duration INTERVAL,
    memory_used INTEGER,
    container_id VARCHAR(255),
    executor_id VARCHAR(255) NOT NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    started_at TIMESTAMP,
    completed_at TIMESTAMP
);

-- Create indexes for better query performance
CREATE INDEX idx_functions_app_id ON functions(app_id);
CREATE INDEX idx_functions_runtime ON functions(runtime);
CREATE INDEX idx_functions_created_at ON functions(created_at);

CREATE INDEX idx_executions_function_id ON executions(function_id);
CREATE INDEX idx_executions_status ON executions(status);
CREATE INDEX idx_executions_executor_id ON executions(executor_id);
CREATE INDEX idx_executions_created_at ON executions(created_at);

-- Create trigger to update updated_at timestamp
CREATE OR REPLACE FUNCTION update_updated_at_column()
RETURNS TRIGGER AS $$
BEGIN
    NEW.updated_at = CURRENT_TIMESTAMP;
    RETURN NEW;
END;
$$ language 'plpgsql';

CREATE TRIGGER update_functions_updated_at 
    BEFORE UPDATE ON functions 
    FOR EACH ROW EXECUTE FUNCTION update_updated_at_column();

-- Insert some default runtime configurations
COMMENT ON TABLE functions IS 'Function definitions and configurations';
COMMENT ON TABLE executions IS 'Function execution records and results';

-- Create a view for function statistics
CREATE OR REPLACE VIEW function_stats AS
SELECT 
    f.id,
    f.name,
    f.app_id,
    f.runtime,
    COUNT(e.id) as total_executions,
    COUNT(CASE WHEN e.status = 'completed' THEN 1 END) as successful_executions,
    COUNT(CASE WHEN e.status = 'failed' THEN 1 END) as failed_executions,
    COUNT(CASE WHEN e.status = 'running' THEN 1 END) as running_executions,
    AVG(EXTRACT(epoch FROM e.duration)) as avg_duration_seconds,
    MAX(e.created_at) as last_execution_at
FROM functions f
LEFT JOIN executions e ON f.id = e.function_id
GROUP BY f.id, f.name, f.app_id, f.runtime;