-- Auth tables for login/register (sys_users + user_sessions)

-- See docs/dev/backend/auth.md



CREATE TABLE IF NOT EXISTS sys_users (

    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),

    account VARCHAR(100) NOT NULL,

    password_hash TEXT NOT NULL,

    name VARCHAR(100) NOT NULL,

    email VARCHAR(255) NOT NULL,

    phone VARCHAR(50),

    created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),

    updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()

);



CREATE UNIQUE INDEX IF NOT EXISTS ux_users_account ON sys_users (account);

CREATE UNIQUE INDEX IF NOT EXISTS ux_users_email ON sys_users (email);



CREATE TABLE IF NOT EXISTS user_sessions (

    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),

    user_id UUID NOT NULL REFERENCES sys_users (id) ON DELETE CASCADE,

    jti VARCHAR(64) NOT NULL,

    token_hash TEXT NOT NULL,

    expires_at TIMESTAMPTZ NOT NULL,

    revoked_at TIMESTAMPTZ,

    created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),

    updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()

);



CREATE UNIQUE INDEX IF NOT EXISTS ux_user_sessions_jti ON user_sessions (jti);

CREATE INDEX IF NOT EXISTS ix_user_sessions_user_id ON user_sessions (user_id);

