CREATE TABLE IF NOT EXISTS auth_identities (
  id TEXT PRIMARY KEY,
  user_id TEXT NOT NULL,
  provider TEXT NOT NULL,
  provider_uid TEXT NOT NULL,
  provider_unionid TEXT,
  display_name TEXT,
  avatar_url TEXT,
  is_verified BOOLEAN NOT NULL DEFAULT TRUE,
  meta_json JSONB,
  created_at TEXT NOT NULL,
  updated_at TEXT NOT NULL,
  FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
);

CREATE UNIQUE INDEX IF NOT EXISTS auth_identities_provider_uid_unique_idx
  ON auth_identities (provider, provider_uid);

CREATE UNIQUE INDEX IF NOT EXISTS auth_identities_provider_unionid_unique_idx
  ON auth_identities (provider, provider_unionid)
  WHERE provider_unionid IS NOT NULL;

CREATE INDEX IF NOT EXISTS auth_identities_user_idx
  ON auth_identities (user_id, provider);
