CREATE TABLE IF NOT EXISTS plugin_installations (
    id                      BIGSERIAL PRIMARY KEY,
    tenant_id               BIGINT NOT NULL REFERENCES tenants(id),
    user_id                 BIGINT NOT NULL REFERENCES users(id),
    installation_key        VARCHAR(128) NOT NULL,
    installation_name       VARCHAR(255) NOT NULL,
    browser_name            VARCHAR(64),
    client_version          VARCHAR(32),
    installation_token_hash VARCHAR(128) NOT NULL,
    status                  VARCHAR(20) NOT NULL DEFAULT 'active',
    last_seen_at            TIMESTAMPTZ,
    created_at              TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    updated_at              TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    deleted_at              TIMESTAMPTZ
);

CREATE UNIQUE INDEX IF NOT EXISTS uk_plugin_installations_key_active
    ON plugin_installations(tenant_id, installation_key)
    WHERE deleted_at IS NULL;

CREATE INDEX IF NOT EXISTS idx_plugin_installations_tenant_status
    ON plugin_installations(tenant_id, status, created_at DESC);

ALTER TABLE plugin_sessions
    ADD COLUMN IF NOT EXISTS plugin_installation_id BIGINT;

DO $$
BEGIN
    IF NOT EXISTS (
        SELECT 1
        FROM pg_constraint
        WHERE conname = 'plugin_sessions_plugin_installation_id_fkey'
    ) THEN
        ALTER TABLE plugin_sessions
            ADD CONSTRAINT plugin_sessions_plugin_installation_id_fkey
            FOREIGN KEY (plugin_installation_id)
            REFERENCES plugin_installations(id);
    END IF;
END $$;
