import {
  AttendanceModel,
  attendanceValidationSchema,
} from "../models/attendance";
import { Request, Response } from "express";

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

  try {
    const { attendances } = req.body;

    // ✅ Bulk insert
    const createdAttendances = await AttendanceModel.bulkCreate(attendances, {
      validate: true,
    });

    return res.status(200).json({
      message: "Attendance marked successfully.",
      count: createdAttendances.length,
    });
  } catch (ex) {
    console.error(ex);
    return res.status(500).json({
      error: ex,
    });
  }
};

/// Get all attendances
export const getAllAttendances = async (req: Request, res: Response) => {
  try {
    const attendances = await AttendanceModel.findAll({
      where: { isDeleted: false },
    });
    return res.status(200).json(attendances);
  } catch (ex) {
    return res.status(500).json({ error: "An unexpected error occurred." });
  }
};

/// Update existing attendance
export const updateAttendance = async (req: Request, res: Response) => {
  try {
    // Find the attendance by ID
    const attendance = await AttendanceModel.findByPk(req.params.id);
    if (!attendance)
      return res.status(404).json({ error: "Attendance not found." });

    // Validate the request body
    const { error } = attendanceValidationSchema.validate(req.body);
    if (error) return res.status(400).json({ error: error.details[0].message });

    // Update the attendance details
    await attendance.update(req.body);

    // Send success response
    return res
      .status(200)
      .json({ message: "Attendance updated successfully.", id: attendance.id });
  } catch (ex) {
    console.error(`Error updating attendance: ${ex}`);
    return res.status(500).json({ error: "An unexpected error occurred." });
  }
};

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

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

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