const db = require("../../db");
const bcrypt = require("bcryptjs");

exports.createStudent = async (req, res) => {
  try {
    console.log(db.StudentMBA);
    const { fullName, agentName, email, mobile, gender, city, password } =
      req.body;

    // Validate required fields
    if (
      !fullName ||
      !agentName ||
      !email ||
      !mobile ||
      !gender ||
      !city ||
      !password
    ) {
      return res.status(400).json({
        success: false,
        error: "All fields are required",
      });
    }

    // Check if email already exists
    const existingStudent = await db.StudentMBA.findOne({
      where: { email },
    });

    if (existingStudent) {
      return res.status(400).json({
        success: false,
        error: "Email already exists",
      });
    }

    // Create new student
    const newStudent = await db.StudentMBA.create({
      full_name: fullName,
      agent_name: agentName,
      email,
      mobile,
      gender,
      city,
      password, // Password will be hashed by the model hook
    });

    // Don't return password in response
    const studentResponse = {
      student_id: newStudent.student_id,
      full_name: newStudent.full_name,
      agent_name: newStudent.agent_name,
      email: newStudent.email,
      mobile: newStudent.mobile,
      gender: newStudent.gender,
      city: newStudent.city,
      created_at: newStudent.created_at,
    };

    res.status(201).json({
      success: true,
      message: "Student created successfully",
      data: studentResponse,
    });
  } catch (err) {
    console.error("Error creating student:", err);
    res.status(500).json({
      success: false,
      error: "Failed to create student",
    });
  }
};

exports.getAllStudents = async (req, res) => {
  try {
    const students = await db.StudentMBA.findAll({
      attributes: { exclude: ["password"] }, // Don't return passwords
      order: [["created_at", "DESC"]],
    });

    res.json({
      success: true,
      data: students,
    });
  } catch (err) {
    console.error("Error fetching students:", err);
    res.status(500).json({
      success: false,
      error: "Failed to fetch students",
    });
  }
};

exports.getStudentById = async (req, res) => {
  try {
    const { id } = req.params;

    const student = await db.StudentMBA.findByPk(id, {
      attributes: { exclude: ["password"] },
    });

    if (!student) {
      return res.status(404).json({
        success: false,
        error: "Student not found",
      });
    }

    res.json({
      success: true,
      data: student,
    });
  } catch (err) {
    console.error("Error fetching student:", err);
    res.status(500).json({
      success: false,
      error: "Failed to fetch student",
    });
  }
};

exports.updateStudent = async (req, res) => {
  try {
    const { id } = req.params;
    const { fullName, agentName, email, mobile, gender, city, password } =
      req.body;

    const student = await db.StudentMBA.findByPk(id);
    if (!student) {
      return res.status(404).json({
        success: false,
        error: "Student not found",
      });
    }

    // Check if email is being changed to one that already exists
    if (email && email !== student.email) {
      const existingStudent = await db.StudentMBA.findOne({ where: { email } });
      if (existingStudent) {
        return res.status(400).json({
          success: false,
          error: "Email already exists",
        });
      }
    }

    // Update student
    const updatedData = {
      full_name: fullName || student.full_name,
      agent_name: agentName || student.agent_name,
      email: email || student.email,
      mobile: mobile || student.mobile,
      gender: gender || student.gender,
      city: city || student.city,
    };

    // Only update password if provided
    if (password) {
      updatedData.password = password;
    }

    await student.update(updatedData);

    // Don't return password in response
    const studentResponse = {
      student_id: student.student_id,
      full_name: student.full_name,
      agent_name: student.agent_name,
      email: student.email,
      mobile: student.mobile,
      gender: student.gender,
      city: student.city,
      updated_at: student.updated_at,
    };

    res.json({
      success: true,
      message: "Student updated successfully",
      data: studentResponse,
    });
  } catch (err) {
    console.error("Error updating student:", err);
    res.status(500).json({
      success: false,
      error: "Failed to update student",
    });
  }
};

exports.deleteStudent = async (req, res) => {
  try {
    const { id } = req.params;

    const student = await db.StudentMBA.findByPk(id);
    if (!student) {
      return res.status(404).json({
        success: false,
        error: "Student not found",
      });
    }

    await student.destroy();

    res.json({
      success: true,
      message: "Student deleted successfully",
    });
  } catch (err) {
    console.error("Error deleting student:", err);
    res.status(500).json({
      success: false,
      error: "Failed to delete student",
    });
  }
};
