import { json } from "stream/consumers";
import Notification from "../models/notification";
import User from "../models/user";
import { getMessaging } from "firebase-admin/messaging";
import NotificationSettings from "../models/notificationSettings";
import { createMessage } from "./twilio";
import { occasionIdOf } from "../utils/occasion";

export const createNewNotification = async (
  userId: string,
  type: string,
  options: {
    title: string;
    description: string;
    imageURL?: string;
    sendPushNotification?: boolean;
    saveNotification?: boolean;
    event?: string;
    occasion?: string;
  },
) => {
  console.log("createNewNotification called with options:", options); // Log the options to see what is being passed
  try {
    await User.findById(userId)
      .then(async (user: typeof User) => {
        const notification = new Notification({
          title: options.title,
          description: options.description,
          user: user._id,
          isRead: false,
          type: type,
          event: options.event,
          occasion: options.occasion,
        });

        if (options.saveNotification !== false) {
          await notification.save().catch((e: Error) => console.log(e));
        }

        if (options.sendPushNotification) {
          const message = {
            data: {
              title: options.title,
              description: options.description,
              imageURL: options.imageURL || "",
            },
            token: user.FCMToken,
          };
          console.log("Sending push notification with message:", message); // Log the message being sent
          getMessaging()
            .send(message)
            .then((response) => {
              // Response is a message ID string.
              console.log("Successfully sent message:", response);
            })
            .catch((error) => {
              console.log("Error sending message:", error);
            });
        }
      })
      .catch((err: Error) => {
        console.log(err);
      });
  } catch (err) {
    console.log(err);
  }
};

export const sendEventNotification = async (event: any) => {
  try {
    const user = await User.findById(event.user);
    const notificationSettings = await NotificationSettings.findOne({
      user: user._id,
    });

    console.log("notificationSettings", notificationSettings); //notificationSettings

    if (notificationSettings && notificationSettings?.pushNotification?.event) {
      createNewNotification(user._id, "event", {
        title: "Event Reminder",
        description: "You have an event: " + event.title,
        sendPushNotification: true,
        saveNotification: true,
        event: event._id,
        occasion: occasionIdOf(event.occasion),
      });
    }

    createMessage(
      event.recipientPhone,
      event.note,
      `${user.signature || `— From ${user?.name}`}\n\nThis is an automated message, please do not reply.`,
    );
  } catch (err) {
    console.log(err);
  }
};
