import {
  SessionModel,
  sessionValidationSchema,
  updateSessionValidationSchema,
} from "../models/session";
import { Request, Response } from "express";

/// Create new session
export const createSession = async (req: Request, res: Response) => {
  console.log("Request Body:", req.body); // Debugging line
  const { error } = sessionValidationSchema.validate(req.body);
  if (error) {
    return res.status(400).json({ error: error.details[0].message });
  }

  try {
    const session = await SessionModel.create(req.body);
    res
      .status(200)
      .json({ messae: "Session created successfully", id: session.id });
  } catch (err) {
    return res.status(500).json({ error: "Internal Server Error" });
  }
};

/// Get all sessions
export const getAllSessions = async (req: Request, res: Response) => {
  try {
    const sessions = await SessionModel.findAll({
      where: { isDeleted: 0, classId: req.params.id },
    });
    return res.status(200).json(sessions);
  } catch (err) {
    return res.status(500).json({ error: "Internal server error" });
  }
};

export const updateSession = async (req: Request, res: Response) => {
  try {
    const session = await SessionModel.findByPk(req.params.id);
    if (!session) return res.status(404).json({ error: "Session not found." });

    const { error } = updateSessionValidationSchema.validate(req.body, {
      allowUnknown: true,
    });
    if (error) return res.status(400).json({ error: error.details[0].message });

    await session.update(req.body);

    res
      .status(200)
      .json({ message: "Session updated successfully.", data: session });
  } catch (ex) {
    console.error(ex);
    res.status(500).json({ error: "Internal server error" });
  }
};

/// Delete session
export const deleteSession = async (req: Request, res: Response) => {
  try {
    // Find the session by ID
    const session = await SessionModel.findByPk(req.params.id);
    if (!session) return res.status(404).json({ error: "Session not found." });

    // Soft delete the session
    await session.update({ isDeleted: true });

    // Send success response
    res.status(200).json({ message: "Session deleted successfully." });
  } catch (ex) {
    res.status(500).json({ error: "An unexpected error occurred." });
  }
};
