--
-- New items
--

-- Accounts
CREATE TABLE arimelody.account (
    id UUID DEFAULT gen_random_uuid(), 
    username TEXT NOT NULL UNIQUE, 
    password TEXT NOT NULL, 
    email TEXT,
    avatar_url TEXT,
    created_at TIMESTAMP DEFAULT current_timestamp
);
ALTER TABLE arimelody.account ADD CONSTRAINT account_pk PRIMARY KEY (id);

-- Privilege
CREATE TABLE arimelody.privilege (
    account UUID NOT NULL, 
    privilege TEXT NOT NULL
);
ALTER TABLE arimelody.privilege ADD CONSTRAINT privilege_pk PRIMARY KEY (account, privilege);

-- Invites
CREATE TABLE arimelody.invite (
    code text NOT NULL, 
    created_at TIMESTAMP NOT NULL DEFAULT current_timestamp, 
    expires_at TIMESTAMP NOT NULL
);
ALTER TABLE arimelody.invite ADD CONSTRAINT invite_pk PRIMARY KEY (code);

-- Sessions
CREATE TABLE arimelody.session (
    token TEXT,
    user_agent TEXT NOT NULL,
    created_at TIMESTAMP NOT NULL DEFAULT current_timestamp,
    expires_at TIMESTAMP DEFAULT NULL,
    account UUID,
    message TEXT,
    error TEXT
);
ALTER TABLE arimelody.session ADD CONSTRAINT session_pk PRIMARY KEY (token);

-- TOTP methods
CREATE TABLE arimelody.totp (
    name TEXT NOT NULL,
    account UUID NOT NULL,
    secret TEXT,
    created_at TIMESTAMP NOT NULL DEFAULT current_timestamp
    confirmed BOOLEAN DEFAULT false,
);
ALTER TABLE arimelody.totp ADD CONSTRAINT totp_pk PRIMARY KEY (account, name);

-- Foreign keys
ALTER TABLE arimelody.privilege ADD CONSTRAINT privilege_account_fk FOREIGN KEY (account) REFERENCES account(id) ON DELETE CASCADE;
ALTER TABLE arimelody.token ADD CONSTRAINT token_account_fk FOREIGN KEY (account) REFERENCES account(id) ON DELETE CASCADE;
ALTER TABLE arimelody.totp ADD CONSTRAINT totp_account_fk FOREIGN KEY (account) REFERENCES account(id) ON DELETE CASCADE;
