import { mailService } from "../../infrastructure/mail/mail.service";
import * as notificationRepo from "./notification.repo";

// export async function sendEmailNotification(data: {
//   userId: string;
//   title: string;
//   message: string;
// }) {
//   const user = await notificationRepo.getUserContact(data.userId);
//   if (!user) throw new Error("User not found");

//   const notification = await notificationRepo.createNotification({
//     userId: data.userId,
//     channel: "EMAIL",
//     title: data.title,
//     message: data.message,
//   });

//   try {
//     if (!user.email) throw new Error("User has no email");

//     const sent = await mailService.sendMail({
//       to: user.email,
//       subject: data.title,
//       html: `
//         <h2>${data.title}</h2>
//         <p>Hello ${user.name},</p>
//         <p>${data.message}</p>
//       `,
//       text: `Hello ${user.name}, ${data.message}`,
//     });

//     if (!sent) throw new Error("sendMail returned false");

//     await notificationRepo.markAsSent(notification.id);
//     return { status: "SENT" };
//   } catch (error) {
//     await notificationRepo.markAsFailed(notification.id);
//     return { status: "FAILED", error: (error as Error).message };
//   }
// }

export async function sendEmailNotification(data: {
  userId: string;
  title: string;
  message: string;
  actionUrl?: string;
  actionLabel?: string;
  companyName?: string;
  skipEmail?: boolean;
}) {
  const user = await notificationRepo.getUserContact(data.userId);
  if (!user) throw new Error("User not found");

  const notification = await notificationRepo.createNotification({
    userId: data.userId,
    channel: "EMAIL",
    title: data.title,
    message: data.message,
  });

  if (data.skipEmail) {
    await notificationRepo.markAsSent(notification.id);
    return { status: "SENT" };
  }

  try {
    if (!user.email) throw new Error("User has no email");

    const sent = await mailService.sendNotificationEmail({
      to: user.email,
      userName: user.name,
      title: data.title,
      message: data.message,
      actionUrl: data.actionUrl,
      actionLabel: data.actionLabel ?? "View Details",
      companyName: data.companyName ?? "TaxFend",
    });

    if (!sent) throw new Error("sendMail returned false");

    await notificationRepo.markAsSent(notification.id);
    return { status: "SENT" };
  } catch (error) {
    await notificationRepo.markAsFailed(notification.id);
    return { status: "FAILED", error: (error as Error).message };
  }
}
