-- +goose Up
-- +goose StatementBegin
CREATE TABLE IF NOT EXISTS users
(
    id          serial             NOT NULL,
    username    VARCHAR(70) UNIQUE NOT NULL,
    hashed_pwd  VARCHAR(60)        NOT NULL,
    role        INT                NOT NULL DEFAULT 0,
    created_at  TIMESTAMPTZ        NOT NULL DEFAULT NOW(),
    modified_at TIMESTAMPTZ        NOT NULL DEFAULT NOW(),

    PRIMARY KEY (id),
    CHECK (length(username) != 0 AND username = lower(username) AND username = trim(username)),
    CHECK (length(hashed_pwd) != 0),
    CHECK (role BETWEEN 0 AND 2)
);

CREATE FUNCTION modified_at_update() RETURNS TRIGGER
    LANGUAGE plpgsql AS
$$
BEGIN
    NEW.modified_at = NOW();
    RETURN NEW;
END;
$$;

CREATE TRIGGER on_users_update
    BEFORE UPDATE
    ON users
    FOR EACH ROW
EXECUTE PROCEDURE modified_at_update();
-- +goose StatementEnd

-- +goose Down
DROP TABLE IF EXISTS users;