CREATE TABLE "external_auth" (
  "name"          text NOT NULL,
  "oidc_url"      text NULL,
  "auth_url"      text NOT NULL,
  "token_url"     text NOT NULL,
  "client_key"    text NOT NULL,
  "client_secret" text NOT NULL,
  "created_at"    timestamptz NOT NULL DEFAULT now(),
  PRIMARY KEY ("name")
);
CREATE UNIQUE INDEX "external_auth_name_key" ON "external_auth" ("name");

CREATE TABLE "external_user" (
  "identity_id"        bigint NOT NULL,
  "external_auth_name" text NOT NULL,
  "external_id"        text NOT NULL,
  "auth_token"         text NULL,
  "refresh_token"      text NULL,
  "identity_token"     text NULL,
  FOREIGN KEY ("identity_id")
    REFERENCES "identity" ("id")
    ON UPDATE RESTRICT
    ON DELETE CASCADE,
  FOREIGN KEY ("external_auth_name")
    REFERENCES "external_auth" ("name")
    ON UPDATE CASCADE
    ON DELETE CASCADE,
  PRIMARY KEY ("identity_id")
);
CREATE INDEX "external_user_external_auth_name_idx"
  ON "external_user" ("external_auth_name");
CREATE UNIQUE INDEX "external_user_external_id_key"
  ON "external_user" ("external_auth_name", "external_id");