import { d as db, e as communicationLogs } from '../../admin/create-upload-progress-table/POST-C-OoiMoW.js';
import crypto from 'crypto';

async function handler(req, res) {
  try {
    const { serverId, deviceId, notificationType, title, message, data } = req.body;
    if (!serverId || !notificationType || !title || !message) {
      return res.status(400).json({
        success: false,
        error: "Missing required fields: serverId, notificationType, title, and message are required"
      });
    }
    const messageId = crypto.randomBytes(16).toString("hex");
    const metadata = {
      notificationType,
      title,
      data: data || {}
    };
    const result = await db.insert(communicationLogs).values({
      messageId,
      fromType: "server",
      fromId: serverId,
      toType: "device",
      toId: deviceId || null,
      messageType: "notification",
      subject: title,
      body: message,
      metadata: JSON.stringify(metadata),
      status: "sent"
    });
    const insertId = Number(result[0].insertId);
    const newNotification = await db.select().from(communicationLogs).where((logs) => logs.id === insertId).limit(1);
    if (newNotification.length === 0) {
      return res.status(500).json({
        success: false,
        error: "Failed to retrieve created notification"
      });
    }
    res.status(201).json({
      success: true,
      notification: newNotification[0]
    });
  } catch (error) {
    console.error("Notification send error:", error);
    res.status(500).json({
      success: false,
      error: "Failed to send notification",
      message: String(error)
    });
  }
}

export { handler as h };
