import { g as generateEncryptionKey, d as deriveKeyFromPassword } from '../../backup/download-decrypted/_backupId_/GET-D4n5HIiX.js';
import { d as db, c as devices } from '../../admin/create-upload-progress-table/POST-C-OoiMoW.js';
import { eq } from 'drizzle-orm';

async function handler(req, res) {
  try {
    const { deviceId, method, password } = req.body;
    if (!deviceId) {
      return res.status(400).json({
        success: false,
        error: "Device ID is required"
      });
    }
    if (!method || !["random", "password"].includes(method)) {
      return res.status(400).json({
        success: false,
        error: 'Method must be "random" or "password"'
      });
    }
    if (method === "password" && !password) {
      return res.status(400).json({
        success: false,
        error: "Password is required for password-based key generation"
      });
    }
    const device = await db.select().from(devices).where(eq(devices.deviceId, deviceId)).limit(1);
    if (device.length === 0) {
      return res.status(404).json({
        success: false,
        error: "Device not found"
      });
    }
    let key;
    let salt;
    if (method === "random") {
      key = generateEncryptionKey();
    } else {
      const result = deriveKeyFromPassword(password);
      key = result.key;
      salt = result.salt;
    }
    const encryptedKey = key.toString("base64");
    await db.update(devices).set({ encryptionKey: encryptedKey }).where(eq(devices.deviceId, deviceId));
    const response = {
      success: true,
      key: key.toString("base64")
    };
    if (salt) {
      response.salt = salt.toString("base64");
    }
    res.json(response);
  } catch (error) {
    console.error("Key generation error:", error);
    res.status(500).json({
      success: false,
      error: "Failed to generate encryption key",
      message: String(error)
    });
  }
}

export { handler as h };
