import { d as db, g as servers } from '../../admin/create-upload-progress-table/POST-C-OoiMoW.js';
import { eq } from 'drizzle-orm';
import crypto from 'crypto';

async function handler(req, res) {
  try {
    const { serverId, name, type, ipAddress, port, storageTotal, storageUsed } = req.body;
    if (!serverId || !name || !type) {
      return res.status(400).json({
        success: false,
        error: "Missing required fields: serverId, name, and type are required"
      });
    }
    if (type !== "pc" && type !== "cloud") {
      return res.status(400).json({
        success: false,
        error: 'Invalid type. Must be "pc" or "cloud"'
      });
    }
    const existingServer = await db.select().from(servers).where(eq(servers.serverId, serverId)).limit(1);
    if (existingServer.length > 0) {
      return res.status(409).json({
        success: false,
        error: "Server already registered",
        server: existingServer[0]
      });
    }
    const apiKey = crypto.randomBytes(32).toString("hex");
    const result = await db.insert(servers).values({
      serverId,
      name,
      type,
      ipAddress: ipAddress || null,
      port: port || 8080,
      apiKey,
      status: "online",
      storageTotal: storageTotal || null,
      storageUsed: storageUsed || null,
      storageAllocated: 0,
      lastPing: /* @__PURE__ */ new Date()
    });
    const insertId = Number(result[0].insertId);
    const newServer = await db.select().from(servers).where(eq(servers.id, insertId)).limit(1);
    if (newServer.length === 0) {
      return res.status(500).json({
        success: false,
        error: "Failed to retrieve created server"
      });
    }
    res.status(201).json({
      success: true,
      server: newServer[0]
    });
  } catch (error) {
    console.error("Server registration error:", error);
    res.status(500).json({
      success: false,
      error: "Failed to register server",
      message: String(error)
    });
  }
}

export { handler as h };
