import type { Response, NextFunction } from "express";
import type { AuthenticatedRequest } from "../types/express.js";
import { GameRequestSchema, AnswerSubmissionSchema } from "@lila/shared";
import { createGameSession, evaluateAnswer } from "../services/gameService.js";
import { ValidationError } from "../errors/AppError.js";
import type { GameSessionStore } from "../gameSessionStore/index.js";

export const createGameController = (store: GameSessionStore) => ({
  createGame: async (
    req: AuthenticatedRequest,
    res: Response,
    next: NextFunction,
  ) => {
    try {
      const gameSettings = GameRequestSchema.safeParse(req.body);
      if (!gameSettings.success) {
        throw new ValidationError("Invalid game settings");
      }
      const gameQuestions = await createGameSession(
        gameSettings.data,
        store,
        req.session.user.id,
      );
      res.json({ success: true, data: gameQuestions });
    } catch (error) {
      next(error);
    }
  },

  submitAnswer: async (
    req: AuthenticatedRequest,
    res: Response,
    next: NextFunction,
  ) => {
    try {
      const submission = AnswerSubmissionSchema.safeParse(req.body);
      if (!submission.success) {
        throw new ValidationError("Invalid answer submission");
      }
      const result = await evaluateAnswer(
        submission.data,
        store,
        req.session.user.id,
      );
      res.json({ success: true, data: result });
    } catch (error) {
      next(error);
    }
  },
});
