CREATE SCHEMA IF NOT EXISTS administration;

CREATE TABLE IF NOT EXISTS administration.api_keys
(
    Id         SERIAL PRIMARY KEY,
    Identifier VARCHAR(255) NOT NULL,
    KeyString  VARCHAR(255) NOT NULL,
    -- for history
    Deleted    BOOLEAN      NOT NULL DEFAULT FALSE,
    EditorId   INT          NULL REFERENCES administration.users (Id),
    CreatedUtc timestamptz  NOT NULL DEFAULT NOW(),
    UpdatedUtc timestamptz  NOT NULL DEFAULT NOW(),

    CONSTRAINT UC_Identifier_Key UNIQUE (Identifier, KeyString),
    CONSTRAINT UC_Key UNIQUE (KeyString)
);

CREATE TABLE IF NOT EXISTS administration.api_keys_history
(
    LIKE administration.api_keys
);

CREATE TRIGGER api_keys_history_trigger
    BEFORE INSERT OR UPDATE OR DELETE
    ON administration.api_keys
    FOR EACH ROW
EXECUTE FUNCTION public.history_trigger_function();

