-- This file is used for generating queries; If you change anything please
-- also add migrations in `assets/migrations`.

CREATE TABLE "user" (
  "id"         bigserial NOT NULL,
  "is_admin"   boolean NOT NULL DEFAULT false,
  "password"   bytea NULL,
  "created_at" timestamptz NOT NULL DEFAULT NOW(),
  PRIMARY KEY ("id")
);

CREATE TABLE "email" (
  "address"      text NOT NULL,
  "user_id"      bigint NOT NULL,
  "created_at"   timestamptz NOT NULL DEFAULT NOW(),
  FOREIGN KEY ("user_id") REFERENCES "user" ("id") ON DELETE CASCADE,
  PRIMARY KEY ("address")
);
CREATE INDEX ON "email" ("user_id");

CREATE TABLE "confirmation" (
  "email_address" text NOT NULL,
  "user_id"       bigint NOT NULL,
  "selector"      text NOT NULL,
  "verifier"      bytea NOT NULL, -- hashed
  "expires_at"    timestamptz NOT NULL DEFAULT NOW(),
  FOREIGN KEY ("user_id") REFERENCES "user" ("id") ON DELETE CASCADE,
  PRIMARY KEY ("selector")
);
CREATE INDEX ON "confirmation" ("user_id");

CREATE TABLE "reset" (
  "user_id"    bigint NOT NULL,
  "selector"   text NOT NULL,
  "verifier"   bytea NOT NULL, -- hashed
  "expires_at" timestamptz NOT NULL DEFAULT NOW(),
  FOREIGN KEY ("user_id") REFERENCES "user" ("id") ON DELETE CASCADE,
  PRIMARY KEY ("selector")
);
CREATE UNIQUE INDEX ON "reset" ("user_id");

CREATE TABLE "external_auth" (
  "id"           bigserial NOT NULL,
  "name"         text NOT NULL,
  "type"         text NOT NULL,
  "config"       jsonb NOT NULL,
  PRIMARY KEY ("id")
);
CREATE INDEX ON "external_auth" ("type");

CREATE TABLE "external_user" (
  "external_auth_id" bigint NOT NULL,
  "foreign_id"       text NOT NULL,
  "user_id"          bigint NOT NULL,
  FOREIGN KEY ("user_id") REFERENCES "user" ("id") ON DELETE CASCADE,
  FOREIGN KEY ("external_auth_id") REFERENCES "external_auth" ("id") ON DELETE CASCADE,
  PRIMARY KEY ("external_auth_id", "foreign_id")
);