import { Attendance } from "./AttendanceModel.js";

// Mark attendance
export const markAttendance = async (req, res) => {
  try {
    const { date, time, location, notes } = req.body;
    const userId = req.user._id;
    const userType = req.userType;
    // console.log(req.user);
    // console.log(req.body);
    // Parse the input date
    const [year, month, day] = date.split("/");
    const parsedDate = new Date(Date.UTC(year, month - 1, day));
    const today = new Date();
    today.setUTCHours(0, 0, 0, 0);

    // Check if the date in req.body is not today's date
    if (parsedDate.getTime() !== today.getTime()) {
      return res.status(400).json({
        success: false,
        message: `Attendance can only be marked for today's date: ${
          today.toISOString().split("T")[0]
        }`,
      });
    }

    // Get the start and end of the day to check if the attendance is already marked
    const startOfDay = new Date(parsedDate);
    const endOfDay = new Date(parsedDate);
    endOfDay.setUTCHours(23, 59, 59, 999);

    // Check if the attendance record exists for today
    const existingAttendance = await Attendance.findOne({
      userId,
      userType,
      "records.date": {
        $gte: startOfDay,
        $lte: endOfDay,
      },
    });

    if (existingAttendance) {
      return res.status(400).json({
        success: false,
        message: "Attendance for today is already marked.",
      });
    }

    // Check if attendance record exists for the user
    let attendance = await Attendance.findOne({ userId, userType });

    if (!attendance) {
      // Create a new attendance record if it doesn't exist
      attendance = new Attendance({
        userId,
        userType,
        records: [],
      });
    }

    // Add the new attendance record to the array
    attendance.records.push({ date: startOfDay, time, location, notes });
    await attendance.save();

    res.status(201).json({
      success: true,
      message: "Attendance marked successfully",
      record: { date: startOfDay, time, location, notes },
    });
  } catch (error) {
    console.error("Error marking attendance:", error);
    res.status(500).json({
      success: false,
      message: error.message || "Something went wrong",
    });
  }
};

// Get attendance by user ID
export const getAttendanceByUser = async (req, res) => {
  try {
    const userId = req.user._id;

    const attendance = await Attendance.findOne({
      userId,
    }).populate("userId", "name email");

    if (!attendance) {
      return res.status(404).json({
        success: false,
        message: "No attendance records found for this user.",
      });
    }

    res.status(200).json({
      success: true,
      attendance,
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: error.message || "Something went wrong",
    });
  }
};

// Admin route to get attendance by user ID
export const AdmingetAttendanceByUser = async (req, res) => {
  try {
    const { id } = req.params;
    const { page = 1, show = 10 } = req.query;
    const limit = parseInt(show);
    const skip = (page - 1) * limit;

    // Find attendance records for the given user
    const attendanceDoc = await Attendance.findOne({
      userId: id,
    }).populate("userId", "name email");
// console.log(attendanceDoc);
    if (!attendanceDoc) {
      return res.status(404).json({
        success: false,
        message: "No attendance records found for this user.",
      });
    }

    // Pagination and slicing records
    const totalData = attendanceDoc.records.length;
    const paginatedRecords = attendanceDoc.records.slice(skip, skip + limit);

    res.status(200).json({
      success: true,
      user: attendanceDoc.userId,
      userType: attendanceDoc.userType,
      attendance: paginatedRecords,
      total_data: totalData,
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: error.message || "Something went wrong",
    });
  }
};

// Get today's attendance for admin
export const getTodayAttendance = async (req, res) => {
  try {
    // Step 1: Get today's date in UTC and set the time to start and end of the day
    const today = new Date();
    const todayStartUTC = new Date(
      Date.UTC(
        today.getUTCFullYear(),
        today.getUTCMonth(),
        today.getUTCDate(),
        0,
        0,
        0
      )
    );
    const tomorrowStartUTC = new Date(todayStartUTC);
    tomorrowStartUTC.setUTCDate(todayStartUTC.getUTCDate() + 1); // Start of the next day

    // Step 2: Parse query parameters
    const { page = 1, show = 10 } = req.query;
    const limit = parseInt(show, 10);
    const skip = (page - 1) * limit;

    // Step 3: Aggregate query to get today's attendance records
    const attendances = await Attendance.aggregate([
      { $unwind: "$records" },
      {
        $match: {
          "records.date": {
            $gte: todayStartUTC,
            $lt: tomorrowStartUTC,
          },
        },
      },
      {
        $lookup: {
          from: "salescoordinators",
          localField: "userId",
          foreignField: "_id",
          as: "salesCoOrdinatorUser",
        },
      },
      {
        $lookup: {
          from: "territorymanagers",
          localField: "userId",
          foreignField: "_id",
          as: "territoryManagerUser",
        },
      },
      {
        $addFields: {
          user: {
            $cond: {
              if: { $eq: ["$userType", "SalesCoOrdinator"] },
              then: { $arrayElemAt: ["$salesCoOrdinatorUser", 0] },
              else: { $arrayElemAt: ["$territoryManagerUser", 0] },
            },
          },
        },
      },
      {
        $project: {
          salesCoOrdinatorUser: 0,
          territoryManagerUser: 0,
        },
      },
    ]);
    const totalData = attendances.length;
    const paginatedattendance = attendances.slice(skip, skip + limit);
    // Step 6: Format the response
    const formattedattendance = paginatedattendance.map((record) => ({
      user: record.user
        ? {
            id: record.user._id,
            name: record.user.name,
            email: record.user.email,
            mobileNumber: record.user.mobileNumber,
            userType: record.userType,
            uniqueId: record.user.uniqueId,
          }
        : null,
      date: record.records.date,
      time: record.records.time,
      location: record.records.location,
      notes: record.records.notes,
    }));

    // Send response
    res.status(200).json({
      success: true,
      total_data: totalData,
      attendance: formattedattendance,
      page: parseInt(page, 10),
      limit: limit,
    });
  } catch (error) {
    console.error("Error fetching today’s attendance:", error);
    res.status(500).json({
      success: false,
      message: error.message || "Something went wrong",
    });
  }
};
