CREATE TABLE IF NOT EXISTS "user"
(
    "id"            UUID    NOT NULL PRIMARY KEY DEFAULT uuid_generate_v7(),
    "avatar_url"    VARCHAR,
    "username"      VARCHAR NOT NULL UNIQUE,
    "display_name"  VARCHAR,
    "email"         VARCHAR NOT NULL,
    "password_hash" VARCHAR NOT NULL,
    "bot"           BOOLEAN NOT NULL             DEFAULT FALSE,
    "system"        BOOLEAN NOT NULL             DEFAULT FALSE,
    "settings"      JSONB   NOT NULL             DEFAULT '{}'::JSONB
);

CREATE TABLE IF NOT EXISTS "user_relation"
(
    "user_id"    UUID        NOT NULL CHECK (user_id <> other_id) REFERENCES "user" ("id") ON DELETE CASCADE,
    "other_id"   UUID        NOT NULL CHECK (user_id <> other_id) REFERENCES "user" ("id") ON DELETE CASCADE,
    "type"       INT2        NOT NULL,
    "created_at" TIMESTAMPTZ NOT NULL DEFAULT now(),
    "updated_at" TIMESTAMPTZ NOT NULL DEFAULT now(),
    PRIMARY KEY ("user_id", "other_id")
);

-- create system account
INSERT INTO "user" ("username", "display_name", "email", "password_hash", "bot", "system")
VALUES ('system', 'System', 'system@lionarius.ru', '', TRUE, TRUE);

CREATE OR REPLACE FUNCTION fn_on_user_relation_update()
    RETURNS TRIGGER
    LANGUAGE plpgsql
AS
$$
BEGIN
    IF (TG_OP = 'UPDATE') THEN
        NEW.updated_at := now();
    END IF;

    RETURN NEW;
END;
$$;

CREATE TRIGGER trg_user_relation_update
    BEFORE UPDATE
    ON "user_relation"
    FOR EACH ROW
EXECUTE FUNCTION fn_on_user_relation_update();