import {
  StudentModel,
  studentValidationSchema,
  updateStudentValidationSchema,
} from "../models/student";
import { Request, Response } from "express";

/// Create new student
export const createStudent = async (req: Request, res: Response) => {
  const { error } = studentValidationSchema.validate(req.body);
  if (error) {
    return res.status(400).json({ error: error.details[0].message });
  }

  try {
    const student = await StudentModel.create(req.body);
    res
      .status(200)
      .json({ message: "Student created successfully", id: student.id });
  } catch (err) {
    console.log(`Erro Occired: ${err}`);
    return res.status(500).json({ error: "Internal Server Error" });
  }
};

/// Get all students
export const getAllStudents = async (req: Request, res: Response) => {
  try {
    const students = await StudentModel.findAll({
      where: { isDeleted: 0, sessionId: req.params.id },
    });
    const response = students.map((item) => {
      return {
        ...item.toJSON(),
        upperWear: JSON.parse(item.upperWear.toString()),
        lowerWear: JSON.parse(item.lowerWear.toString()),
        headcover:
          item.headcover !== null
            ? JSON.parse(item.headcover.toString())
            : null,
      };
    });
    return res.status(200).json(response);
  } catch (err) {
    return res.status(500).json({ error: "Internal server error" });
  }
};

export const allStudents = async (req: Request, res: Response) => {
  try {
    const students = await StudentModel.findAll({
      where: { isDeleted: 0,},
    });
    const response = students.map((item) => {
      return {
        ...item.toJSON(),
        upperWear: JSON.parse(item.upperWear.toString()),
        lowerWear: JSON.parse(item.lowerWear.toString()),
        headcover:
          item.headcover !== null
            ? JSON.parse(item.headcover.toString())
            : null,
      };
    });
    return res.status(200).json(response);
  } catch (err) {
    return res.status(500).json({ error: "Internal server error" });
  }
};

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

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

    await student.update(req.body);

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

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

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

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