CREATE SCHEMA Accounts;

CREATE TABLE Accounts.Users (
    id SERIAL PRIMARY KEY,
    email VARCHAR(128) NOT NULL UNIQUE,
    emailVerificationTs TIMESTAMP DEFAULT NULL,
    emailVerificationCode VARCHAR(128),
    passwordHash VARCHAR(512) NOT NULL,
    passwordResetCode VARCHAR(128)
);

CREATE TABLE Accounts.Profile (
    userId INT NOT NULL REFERENCES Accounts.Users(id),
    username VARCHAR(64) NOT NULL,
    birthdate TIMESTAMP NOT NULL,
    height DECIMAL NOT NULL,
    displayUnit UNIT NOT NULL DEFAULT 'Metric'
);

CREATE INDEX profile_userid ON Accounts.Profile USING btree (userId);

CREATE TABLE Accounts.UsersAuth (
    userId INT NOT NULL REFERENCES Accounts.Users(id),
    tokenHash VARCHAR(512) NOT NULL,
    deviceId VARCHAR(64) NOT NULL,
    createdTs TIMESTAMP DEFAULT NOW(),
    sourceIp VARCHAR(32) DEFAULT NULL
);

CREATE INDEX usersauth_userid ON Accounts.UsersAuth USING btree (userId);
