-- Migration: Create SDK States Table
-- Description: Initial schema for SDK state persistence

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

-- Create sdk_states table
CREATE TABLE IF NOT EXISTS sdk_states (
    id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
    tenant_id VARCHAR(255) NOT NULL UNIQUE,
    user_id VARCHAR(255),
    state JSONB NOT NULL,
    version INTEGER DEFAULT 1,
    created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
    updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
);

-- Create index on tenant_id for fast lookups
CREATE INDEX IF NOT EXISTS idx_sdk_states_tenant ON sdk_states(tenant_id);

-- Create index on updated_at for ordering
CREATE INDEX IF NOT EXISTS idx_sdk_states_updated ON sdk_states(updated_at DESC);

-- Create trigger to automatically update updated_at
CREATE OR REPLACE FUNCTION update_sdk_states_updated_at()
RETURNS TRIGGER AS $$
BEGIN
    NEW.updated_at = NOW();
    RETURN NEW;
END;
$$ LANGUAGE plpgsql;

DROP TRIGGER IF EXISTS trigger_sdk_states_updated_at ON sdk_states;
CREATE TRIGGER trigger_sdk_states_updated_at
    BEFORE UPDATE ON sdk_states
    FOR EACH ROW
    EXECUTE FUNCTION update_sdk_states_updated_at();

-- Add comments
COMMENT ON TABLE sdk_states IS 'Stores SDK state for each tenant';
COMMENT ON COLUMN sdk_states.tenant_id IS 'Unique identifier for the tenant';
COMMENT ON COLUMN sdk_states.user_id IS 'User who last modified the state';
COMMENT ON COLUMN sdk_states.state IS 'JSON state object';
COMMENT ON COLUMN sdk_states.version IS 'Version number for optimistic locking';

-- Create cleanup function for old states (optional)
CREATE OR REPLACE FUNCTION cleanup_old_sdk_states(days_old INTEGER DEFAULT 365)
RETURNS INTEGER AS $$
DECLARE
    deleted_count INTEGER;
BEGIN
    DELETE FROM sdk_states
    WHERE updated_at < NOW() - (days_old || ' days')::INTERVAL;

    GET DIAGNOSTICS deleted_count = ROW_COUNT;
    RETURN deleted_count;
END;
$$ LANGUAGE plpgsql;

COMMENT ON FUNCTION cleanup_old_sdk_states IS 'Removes SDK states older than specified days';
