CREATE TABLE IF NOT EXISTS installation_authority (
    id SMALLINT PRIMARY KEY DEFAULT 1,
    install_id TEXT NOT NULL,
    authority_state TEXT NOT NULL DEFAULT 'active',
    product_root_key_fingerprint TEXT NOT NULL DEFAULT '',
    activation_payload JSONB NOT NULL,
    activation_signature TEXT NOT NULL,
    bootstrapped_owner_email TEXT NOT NULL,
    bootstrapped_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    CONSTRAINT installation_authority_singleton_check CHECK (id = 1),
    CONSTRAINT installation_authority_state_check CHECK (authority_state IN ('active', 'recovery_required', 'locked'))
);

CREATE TABLE IF NOT EXISTS platform_role_grants (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
    role TEXT NOT NULL,
    install_id TEXT NOT NULL,
    grant_payload JSONB NOT NULL,
    grant_signature TEXT NOT NULL,
    grant_source TEXT NOT NULL DEFAULT 'installation_activation',
    granted_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    expires_at TIMESTAMPTZ,
    revoked_at TIMESTAMPTZ,
    metadata JSONB NOT NULL DEFAULT '{}'::JSONB,
    CONSTRAINT platform_role_grants_role_check
        CHECK (role IN ('platform_admin', 'platform_recovery_admin')),
    CONSTRAINT platform_role_grants_source_check
        CHECK (grant_source IN ('installation_activation', 'recovery_manifest', 'dev_insecure'))
);

CREATE INDEX IF NOT EXISTS idx_platform_role_grants_user_active
    ON platform_role_grants(user_id, role, revoked_at, expires_at);

CREATE UNIQUE INDEX IF NOT EXISTS idx_platform_role_grants_unique_install_role
    ON platform_role_grants(user_id, role, install_id)
    WHERE revoked_at IS NULL;
