-- Platform Schema Migration 001: Platform Service State
-- Defines storage for onboarding, preferences, profiles, quota alerts, and search history.

CREATE SCHEMA IF NOT EXISTS platform;

-- Dashboard preferences per tenant/user
CREATE TABLE IF NOT EXISTS platform.dashboard_preferences (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    tenant_id TEXT NOT NULL,
    actor_id TEXT NOT NULL,
    preferences JSONB NOT NULL DEFAULT '{}',
    updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    updated_by TEXT,
    UNIQUE(tenant_id, actor_id)
);

CREATE INDEX idx_dashboard_preferences_tenant ON platform.dashboard_preferences(tenant_id);

-- Saved dashboard profiles per tenant
CREATE TABLE IF NOT EXISTS platform.dashboard_profiles (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    tenant_id TEXT NOT NULL,
    profile_id TEXT NOT NULL,
    name TEXT NOT NULL,
    description TEXT,
    preferences JSONB NOT NULL DEFAULT '{}',
    updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    updated_by TEXT,
    UNIQUE(tenant_id, profile_id)
);

CREATE INDEX idx_dashboard_profiles_tenant ON platform.dashboard_profiles(tenant_id);
CREATE INDEX idx_dashboard_profiles_profile ON platform.dashboard_profiles(tenant_id, profile_id);

-- Onboarding state per tenant/user
CREATE TABLE IF NOT EXISTS platform.onboarding_state (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    tenant_id TEXT NOT NULL,
    actor_id TEXT NOT NULL,
    status TEXT NOT NULL,
    steps JSONB NOT NULL DEFAULT '[]',
    skipped_reason TEXT,
    updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    updated_by TEXT,
    UNIQUE(tenant_id, actor_id)
);

CREATE INDEX idx_onboarding_state_tenant ON platform.onboarding_state(tenant_id);

-- Quota alert subscriptions (per tenant)
CREATE TABLE IF NOT EXISTS platform.quota_alerts (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    tenant_id TEXT NOT NULL,
    alert_id TEXT NOT NULL,
    quota_id TEXT NOT NULL,
    severity TEXT NOT NULL,
    threshold NUMERIC(18, 4) NOT NULL,
    condition TEXT NOT NULL,
    created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    created_by TEXT,
    UNIQUE(tenant_id, alert_id)
);

CREATE INDEX idx_quota_alerts_tenant ON platform.quota_alerts(tenant_id);
CREATE INDEX idx_quota_alerts_quota ON platform.quota_alerts(tenant_id, quota_id);

-- Search history (optional, user-scoped)
CREATE TABLE IF NOT EXISTS platform.search_history (
    id BIGSERIAL PRIMARY KEY,
    tenant_id TEXT NOT NULL,
    actor_id TEXT NOT NULL,
    query TEXT NOT NULL,
    sources TEXT[] NOT NULL DEFAULT '{}',
    result_count INT NOT NULL DEFAULT 0,
    created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);

CREATE INDEX idx_search_history_tenant ON platform.search_history(tenant_id);
CREATE INDEX idx_search_history_created ON platform.search_history(tenant_id, created_at DESC);
