import { d as db, c as devices, b as backups } from '../../admin/create-upload-progress-table/POST-C-OoiMoW.js';
import { eq } from 'drizzle-orm';

async function handler(req, res) {
  console.log("🚀 [BACKUP-START] Request received");
  console.log("🚀 [BACKUP-START] Body:", JSON.stringify(req.body, null, 2));
  try {
    const { deviceId, pairingToken, backupType, sizeBytes, totalFiles } = req.body;
    if (!deviceId || !pairingToken || !backupType) {
      console.error("❌ [BACKUP-START] Missing required fields");
      return res.status(400).json({
        success: false,
        error: "Missing required fields: deviceId, pairingToken, and backupType are required"
      });
    }
    if (backupType !== "full" && backupType !== "incremental") {
      console.error("❌ [BACKUP-START] Invalid backup type:", backupType);
      return res.status(400).json({
        success: false,
        error: 'Invalid backupType. Must be "full" or "incremental"'
      });
    }
    console.log("🔍 [BACKUP-START] Looking up device:", deviceId);
    const device = await db.select().from(devices).where(eq(devices.deviceId, deviceId)).limit(1);
    if (device.length === 0) {
      console.error("❌ [BACKUP-START] Device not found:", deviceId);
      return res.status(404).json({
        success: false,
        error: "Device not found"
      });
    }
    console.log("✅ [BACKUP-START] Device found:", device[0].name);
    console.log("🔑 [BACKUP-START] Token comparison:");
    console.log("   Expected (from DB):", device[0].pairingToken?.substring(0, 10) + "...");
    console.log("   Received (from app):", pairingToken?.substring(0, 10) + "...");
    console.log("   Match:", device[0].pairingToken === pairingToken);
    if (device[0].pairingToken !== pairingToken) {
      console.error("❌ [BACKUP-START] Invalid pairing token");
      console.error("   This usually means the mobile app is using an old cached token.");
      console.error("   The app should update its stored token after each pairing response.");
      return res.status(401).json({
        success: false,
        error: "Invalid pairing token. Please re-pair your device."
      });
    }
    console.log("📝 [BACKUP-START] Updating device status");
    await db.update(devices).set({
      isConnected: true,
      lastSeen: /* @__PURE__ */ new Date()
    }).where(eq(devices.id, device[0].id));
    const backupId = `backup_${Date.now()}_${Math.random().toString(36).substring(7)}`;
    console.log("📝 [BACKUP-START] Creating backup record:", { backupId, backupType, sizeBytes });
    const result = await db.insert(backups).values({
      backupId,
      deviceId: device[0].deviceId,
      // Use UUID, not integer ID
      backupType,
      status: "in_progress",
      size: sizeBytes ? Math.floor(sizeBytes / (1024 * 1024)) : null,
      // Convert bytes to MB
      startedAt: /* @__PURE__ */ new Date()
    });
    const insertId = Number(result[0].insertId);
    const newBackup = await db.select().from(backups).where(eq(backups.id, insertId)).limit(1);
    if (newBackup.length === 0) {
      console.error("❌ [BACKUP-START] Failed to retrieve created backup");
      return res.status(500).json({
        success: false,
        error: "Failed to retrieve created backup"
      });
    }
    console.log("✅ [BACKUP-START] Backup created successfully:", newBackup[0].id);
    const response = {
      success: true,
      backup: {
        id: newBackup[0].id,
        backupId: newBackup[0].backupId || "",
        deviceId: newBackup[0].deviceId || "",
        backupType: newBackup[0].backupType || "full",
        status: newBackup[0].status || "in_progress",
        totalSize: sizeBytes || 0,
        uploadedSize: 0,
        fileCount: totalFiles || 0,
        filePath: newBackup[0].filePath || "",
        startedAt: newBackup[0].startedAt?.toISOString() || (/* @__PURE__ */ new Date()).toISOString(),
        completedAt: newBackup[0].completedAt?.toISOString() || ""
      }
    };
    console.log("📤 [BACKUP-START] Sending response:", JSON.stringify(response, null, 2));
    res.status(201).json(response);
  } catch (error) {
    console.error("Backup start error:", error);
    res.status(500).json({
      success: false,
      error: "Failed to start backup",
      message: String(error)
    });
  }
}

export { handler as h };
