import type { Request, Response, NextFunction } from "express";
import { createLobby, joinLobby } from "../services/lobbyService.js";

export const createLobbyHandler = async (
  req: Request,
  res: Response,
  next: NextFunction,
) => {
  try {
    const userId = req.session!.user.id;
    const lobby = await createLobby(userId);
    res.json({ success: true, data: lobby });
  } catch (error) {
    next(error);
  }
};

export const joinLobbyHandler = async (
  req: Request,
  res: Response,
  next: NextFunction,
) => {
  try {
    const userId = req.session!.user.id;
    const code = req.params["code"];
    if (!code) {
      return next(new Error("Missing code param"));
    }
    if (typeof code !== "string") {
      return next(new Error("Missing or invalid code param"));
    }
    const lobby = await joinLobby(code, userId);
    res.json({ success: true, data: lobby });
  } catch (error) {
    next(error);
  }
};
