-- 1. ROLES
CREATE TABLE IF NOT EXISTS roles (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    key VARCHAR(255) UNIQUE NOT NULL,
    name VARCHAR(255) NOT NULL,
    audience VARCHAR(50) NOT NULL, -- INTERNAL or EXTERNAL
    is_active BOOLEAN NOT NULL DEFAULT true,
    created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);

-- 2. ONBOARDING CONFIGS
CREATE TABLE IF NOT EXISTS onboarding_configs (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    role_id UUID NOT NULL REFERENCES roles(id) ON DELETE CASCADE,
    schema_json JSONB NOT NULL,
    version INTEGER NOT NULL DEFAULT 1,
    is_active BOOLEAN NOT NULL DEFAULT true,
    updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);

-- Only one active onboarding config per role at a time
CREATE UNIQUE INDEX IF NOT EXISTS idx_active_onboarding_per_role
    ON onboarding_configs(role_id) WHERE is_active = true;

-- 3. DASHBOARD CONFIGS
CREATE TABLE IF NOT EXISTS dashboard_configs (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    role_id UUID NOT NULL REFERENCES roles(id) ON DELETE CASCADE,
    audience VARCHAR(50) NOT NULL, -- INTERNAL or EXTERNAL
    config_json JSONB NOT NULL,
    version INTEGER NOT NULL DEFAULT 1,
    is_active BOOLEAN NOT NULL DEFAULT true,
    updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);

-- Only one active dashboard config per role+audience combination
CREATE UNIQUE INDEX IF NOT EXISTS idx_active_dashboard_per_role_audience
    ON dashboard_configs(role_id, audience) WHERE is_active = true;

-- 4. RUNTIME CONFIGS
CREATE TABLE IF NOT EXISTS runtime_configs (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    role_id UUID NOT NULL REFERENCES roles(id) ON DELETE CASCADE,
    config_json JSONB NOT NULL,
    version INTEGER NOT NULL DEFAULT 1,
    is_active BOOLEAN NOT NULL DEFAULT true,
    updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);

-- Only one active runtime config per role at a time
CREATE UNIQUE INDEX IF NOT EXISTS idx_active_runtime_per_role
    ON runtime_configs(role_id) WHERE is_active = true;
