CREATE TABLE users (
    id SERIAL PRIMARY KEY,
    uid VARCHAR UNIQUE NOT NULL, -- username as unique identifier
    email VARCHAR NOT NULL,
    email_verified BOOLEAN NOT NULL,
    full_name VARCHAR NOT NULL,
    username VARCHAR NOT NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL
);

CREATE TABLE sessions (
    id SERIAL PRIMARY KEY,
    uid VARCHAR NOT NULL,
    token VARCHAR NOT NULL UNIQUE NOT NULL,
    expires TIMESTAMP,
    last_activity TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
    FOREIGN KEY (uid) REFERENCES users (uid)
);

-- Creating indexes for better performance
CREATE INDEX idx_sessions_last_activity ON sessions (last_activity);
CREATE INDEX idx_sessions_token ON sessions (token);

CREATE TABLE session_ips (
    id SERIAL PRIMARY KEY,
    session_id INTEGER NOT NULL,
    ip_address VARCHAR NOT NULL,
    agent VARCHAR NOT NULL,
    access_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
    FOREIGN KEY (session_id) REFERENCES sessions (id),
    CONSTRAINT session_ips_unique UNIQUE (session_id, ip_address)
);

-- Creating indexes for better performance
CREATE INDEX idx_session_ips_session_id_ip_address ON session_ips (session_id, ip_address);
CREATE INDEX idx_session_ips_access_time ON session_ips (access_time);

