import _RS from "../../helpers/ResponseHelper";
import Order from "../../models/Order";
import OrderDetail from "../../models/OrderDetail";
import Admin from "../../models/Admin";
import Helper from "../../helpers/Helper";
import * as mongoose from "mongoose";

export class CronController {
  static async notAcceptAutoAssignBookingByWasher() {
    try {
      const currentTime = new Date();
      const admin = await Admin.findOne({ _id: Helper.adminId });
      const orders = await Order.find({ assigned_by: admin._id }).sort({
        _id: -1,
      });
      for (const order of orders) {
        if (
          order.order_type == "OnDemand" &&
          order.washer_id == null &&
          order.current_status == "new" &&
          order.not_accept_notification_sent_to_admin == false
        ) {
          const createdDate = new Date(order.created_at);
          const timeDifference = currentTime.getTime() - createdDate.getTime();

          // Check if 5 minutes have passed since order creation
          if (timeDifference >= 5 * 60 * 1000) {
            if (admin?.device_token) {
              const notiAdminTitle =
                "Order is not accepted by any nearby washer";
              const notiAdminDescription = `Order ID ${order.random_order_id} was not accepted by any washer within 5 minutes. You can assign a washer on this order.`;
              Helper.sendNotificationToAdmin(
                order.user_id,
                admin._id,
                notiAdminTitle,
                notiAdminDescription
              );
            }

            // Update the status
            order.not_accept_notification_sent_to_admin = true;
            order.save();
          }
        } else if (order.order_type == "Subscription") {
          const today = new Date();
          const formattedToday = today.toISOString().slice(0, 10);

          const subscriptionOrder: any = await OrderDetail.find({
            order_id: mongoose.Types.ObjectId(order._id),
            order_type: "Subscription",
            current_status: "new",
            not_accept_notification_sent_to_admin: false,
            date: formattedToday,
          });

          if (subscriptionOrder) {
            // Loop For Subscription Orders
            for (const order of subscriptionOrder) {
              const createdDate = new Date(order.date_time_stamp);
              const timeDifference =
                currentTime.getTime() - createdDate.getTime();

              // Check if 3 minutes have passed since order creation
              if (timeDifference >= 3 * 60 * 1000) {
                if (admin?.device_token) {
                  const notiAdminTitle =
                    "Subscription order is not accepted by any nearby washer";
                  const notiAdminDescription = `Order ID ${order.random_order_id} was not accepted by the washer within 3 minutes. You can assign a new washer.`;
                  Helper.sendNotificationToAdmin(
                    order.user_id,
                    admin._id,
                    notiAdminTitle,
                    notiAdminDescription
                  );
                }

                // Update the status
                order.not_accept_notification_sent_to_admin = true;
                order.save();
              }
            }
            // End Subscription Order
          }
        }
      }
    } catch (error) {
      console.error(
        "Not accept booking by washer assigned by automatically, Error in cron job:",
        error
      );
    }
  }

  static async notAcceptAdminAssignBookingByWasher() {
    try {
      const currentTime = new Date();
      const admin = await Admin.findOne({ _id: Helper.adminId });
      const orders = await Order.find({ assigned_by: admin._id }).sort({
        _id: -1,
      });

      for (const order of orders) {
        if (
          order.order_type == "OnDemand" &&
          order.washer_id != null &&
          order.current_status == "assign" &&
          order.not_accept_notification_sent_to_admin == false
        ) {
          const createdDate = new Date(order.created_at);
          const timeDifference = currentTime.getTime() - createdDate.getTime();

          // Check if 3 minutes have passed since order creation
          if (timeDifference >= 3 * 60 * 1000) {
            if (admin?.device_token) {
              const notiAdminTitle =
                "Washer did not accept an order assigned by you";
              const notiAdminDescription = `Order ID ${order.random_order_id} was not accepted by the washer within 3 minutes. You can assign a new washer.`;
              Helper.sendNotificationToAdmin(
                order.user_id,
                admin._id,
                notiAdminTitle,
                notiAdminDescription
              );
            }

            // Update the status
            order.not_accept_notification_sent_to_admin = true;
            order.save();
          }
        } else if (order.order_type == "Subscription") {
          const today = new Date();
          const formattedToday = today.toISOString().slice(0, 10);

          const subscriptionOrder: any = await OrderDetail.find({
            order_id: mongoose.Types.ObjectId(order._id),
            order_type: "Subscription",
            current_status: "assign",
            not_accept_notification_sent_to_admin: false,
            date: formattedToday,
          });

          if (subscriptionOrder) {
            // Loop For Subscription Orders
            for (const order of subscriptionOrder) {
              const createdDate = new Date(order.date_time_stamp);
              const timeDifference =
                currentTime.getTime() - createdDate.getTime();

              // Check if 3 minutes have passed since order creation
              if (timeDifference >= 3 * 60 * 1000) {
                if (admin?.device_token) {
                  const notiAdminTitle =
                    "Washer did not accept an subscription order assigned by you";
                  const notiAdminDescription = `Order ID ${order.random_order_id} was not accepted by the washer within 3 minutes. You can assign a new washer.`;
                  Helper.sendNotificationToAdmin(
                    order.user_id,
                    admin._id,
                    notiAdminTitle,
                    notiAdminDescription
                  );
                }

                // Update the status
                order.not_accept_notification_sent_to_admin = true;
                order.save();
              }
            }
            // End Subscription Order
          }
        }
      }
    } catch (error) {
      console.error(
        "Not accept booking by washer assigned by admin, Error in cron job:",
        error
      );
    }
  }
}
