"use server";

import {prisma} from "@/lib/db/prisma";
import {NotificationChannel} from "@prisma/client";

type DispatchInput = {
  notificationId: string;
  channels?: NotificationChannel[];
};

export async function dispatchNotification({notificationId, channels = ["IN_APP"]}: DispatchInput) {
  try {
    const notification = await prisma.notification.findUnique({
      where: {id: notificationId}
    });

    if (!notification) return {success: false, error: "Notification not found"};

    // Create delivery records for each channel
    const deliveries = await Promise.allSettled(
      channels.map((channel) =>
        prisma.notificationDelivery.create({
          data: {
            notificationId,
            channel,
            status: "SENT",
            sentAt: new Date()
          }
        })
      )
    );

    // Mark notification as SENT if at least one delivery succeeded
    const anySuccess = deliveries.some((d) => d.status === "fulfilled");
    if (anySuccess) {
      await prisma.notification.update({
        where: {id: notificationId},
        data: {status: "SENT"}
      });
    }

    return {success: true};
  } catch {
    return {success: false, error: "Dispatch failed"};
  }
}
