import { usersPool } from "./pools.js";

// ── Schema ────────────────────────────────────────────────────────────────────

export async function initUsersSchema() {
  await usersPool.query(`
    CREATE TABLE IF NOT EXISTS users (
      id SERIAL PRIMARY KEY,
      username TEXT NOT NULL UNIQUE,
      email TEXT NOT NULL UNIQUE,
      password_hash TEXT NOT NULL,
      team TEXT NOT NULL CHECK (team IN ('blue', 'red')),
      role TEXT NOT NULL DEFAULT 'user' CHECK (role IN ('user', 'admin')),
      created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
    );
  `);
}

// ── Queries ───────────────────────────────────────────────────────────────────

export async function createUser(username, email, passwordHash, team) {
  const { rows } = await usersPool.query(
    `INSERT INTO users (username, email, password_hash, team)
     VALUES ($1, $2, $3, $4)
     RETURNING id, username, email, team, role`,
    [username, email, passwordHash, team]
  );
  return rows[0];
}

export async function getUserByUsername(username) {
  const { rows } = await usersPool.query(
    `SELECT id, username, email, team, role, password_hash FROM users WHERE username = $1`,
    [username]
  );
  return rows[0] ?? null;
}

export async function getUserById(id) {
  const { rows } = await usersPool.query(
    `SELECT id, username, email, team, role FROM users WHERE id = $1`,
    [id]
  );
  return rows[0] ?? null;
}