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 { fromType, fromId, toType, toId, messageType, subject, body, metadata } = req.body;
    if (!fromType || !fromId || !toType || !messageType) {
      return res.status(400).json({
        success: false,
        error: "Missing required fields: fromType, fromId, toType, and messageType are required"
      });
    }
    const validTypes = ["device", "server", "dashboard"];
    if (!validTypes.includes(fromType) || !validTypes.includes(toType)) {
      return res.status(400).json({
        success: false,
        error: 'Invalid type. Must be "device", "server", or "dashboard"'
      });
    }
    const validMessageTypes = ["status", "command", "notification", "data"];
    if (!validMessageTypes.includes(messageType)) {
      return res.status(400).json({
        success: false,
        error: 'Invalid messageType. Must be "status", "command", "notification", or "data"'
      });
    }
    const messageId = crypto.randomBytes(16).toString("hex");
    const result = await db.insert(communicationLogs).values({
      messageId,
      fromType,
      fromId,
      toType,
      toId: toId || null,
      messageType,
      subject: subject || null,
      body: body || null,
      metadata: metadata ? JSON.stringify(metadata) : null,
      status: "sent"
    });
    const insertId = Number(result[0].insertId);
    const newMessage = await db.select().from(communicationLogs).where((logs) => logs.id === insertId).limit(1);
    if (newMessage.length === 0) {
      return res.status(500).json({
        success: false,
        error: "Failed to retrieve created message"
      });
    }
    res.status(201).json({
      success: true,
      message: newMessage[0]
    });
  } catch (error) {
    console.error("Message send error:", error);
    res.status(500).json({
      success: false,
      error: "Failed to send message",
      message: String(error)
    });
  }
}

export { handler as h };
