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

async function handler(req, res) {
  try {
    const { deviceId, commandType, parameters } = req.body;
    if (!deviceId || !commandType) {
      return res.status(400).json({
        success: false,
        error: "Missing required fields: deviceId and commandType are required"
      });
    }
    const validCommandTypes = ["backup_now", "pause", "resume", "cancel", "settings_update"];
    if (!validCommandTypes.includes(commandType)) {
      return res.status(400).json({
        success: false,
        error: `Invalid commandType. Must be one of: ${validCommandTypes.join(", ")}`
      });
    }
    const commandId = crypto.randomBytes(16).toString("hex");
    const result = await db.insert(remoteCommands).values({
      commandId,
      deviceId,
      commandType,
      parameters: parameters ? JSON.stringify(parameters) : null,
      status: "pending"
    });
    const insertId = Number(result[0].insertId);
    const newCommand = await db.select().from(remoteCommands).where((cmd) => cmd.id === insertId).limit(1);
    if (newCommand.length === 0) {
      return res.status(500).json({
        success: false,
        error: "Failed to retrieve created command"
      });
    }
    const messageId = crypto.randomBytes(16).toString("hex");
    await db.insert(communicationLogs).values({
      messageId,
      fromType: "dashboard",
      fromId: "system",
      toType: "device",
      toId: deviceId,
      messageType: "command",
      subject: `Remote command: ${commandType}`,
      body: JSON.stringify({ commandId, commandType, parameters }),
      metadata: JSON.stringify({ commandId }),
      status: "sent"
    });
    res.status(201).json({
      success: true,
      command: newCommand[0]
    });
  } catch (error) {
    console.error("Command send error:", error);
    res.status(500).json({
      success: false,
      error: "Failed to send command",
      message: String(error)
    });
  }
}

export { handler as h };
