CREATE TABLE "backend" (
    id TEXT NOT NULL PRIMARY KEY,
    name TEXT NOT NULL UNIQUE,
    oidc_issuer TEXT NOT NULL,
    oidc_client_id TEXT NOT NULL,
    oidc_client_secret TEXT NOT NULL,
    oidc_redirect_uri TEXT NOT NULL,
    oidc_scopes blob NOT NULL DEFAULT '[]' -- list of strings, json-encoded,
);

CREATE TABLE "client" (
    id TEXT NOT NULL PRIMARY KEY,
    secret TEXT NOT NULL,
    redirect_uris blob NOT NULL,
    trusted_peers blob NOT NULL,
    public integer NOT NULL DEFAULT 0,
    name TEXT NOT NULL
);

CREATE TABLE "user" (
    id TEXT NOT NULL PRIMARY KEY,
    name TEXT NOT NULL DEFAULT '',
    family_name TEXT NOT NULL DEFAULT '',
    given_name TEXT NOT NULL DEFAULT '',
    nickname TEXT NOT NULL DEFAULT '',
    picture TEXT NOT NULL DEFAULT '',
    updated_at timestamp,
    email TEXT NOT NULL DEFAULT '',
    email_verified INTEGER NOT NULL DEFAULT 0
);

CREATE TABLE "auth_request" (
    id TEXT NOT NULL PRIMARY KEY,
    client_id TEXT NOT NULL,
    backend_id TEXT NOT NULL,
    scopes blob NOT NULL, -- list of strings, json-encoded
    redirect_uri TEXT NOT NULL,
    state TEXT NOT NULL,
    nonce TEXT NOT NULL,
    response_type TEXT NOT NULL,
    creation_time timestamp NOT NULL,
    done INTEGER NOT NULL DEFAULT 0,
    code_challenge STRING NOT NULL DEFAULT '',
    code_challenge_method STRING NOT NULL DEFAULT '',
    auth_time timestamp,
    user_id TEXT NOT NULL DEFAULT '',
    consent INTEGER NOT NULL DEFAULT 0,
    FOREIGN KEY(backend_id) REFERENCES backend(id),
    FOREIGN KEY(client_id) REFERENCES client(id),
    FOREIGN KEY(user_id) REFERENCES user(id)
);

CREATE TABLE "auth_code" (
    id TEXT NOT NULL PRIMARY KEY,
    code TEXT NOT NULL,
    auth_request_id TEXT NOT NULL,
    FOREIGN KEY(auth_request_id) REFERENCES auth_request(id)
);

CREATE TABLE refresh_token (
    id TEXT NOT NULL PRIMARY KEY,
    client_id TEXT NOT NULL,
    user_id TEXT NOT NULL,
    scopes blob NOT NULL, -- list of strings, json-encoded
    auth_time timestamp NOT NULL,
    FOREIGN KEY(client_id) REFERENCES client(id),
    FOREIGN KEY(user_id) REFERENCES user(id)
);
