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

let validatePairingToken = null;
async function getTokenValidator() {
  if (!validatePairingToken) {
    try {
      const module = await import('../generate-token/POST-Dc5FOr6V.js');
      validatePairingToken = module.validatePairingToken;
      console.log("✅ Token validator loaded successfully");
    } catch (error) {
      console.error("❌ Failed to load token validator:", error);
    }
  }
  return validatePairingToken;
}
function createDeviceFingerprint(name, model, platform) {
  const parts = [
    name.toLowerCase().trim(),
    model?.toLowerCase().trim() || "",
    platform?.toLowerCase().trim() || ""
  ].filter(Boolean);
  return parts.join("|");
}
async function handler(req, res) {
  try {
    const { token, deviceId, name, model, osVersion, platform, storageTotal, storageUsed } = req.body;
    console.log("📱 Device pairing request:", {
      hasToken: !!token,
      deviceId,
      name,
      model,
      platform
    });
    if (!deviceId || !name) {
      console.log("❌ Missing deviceId or name");
      return res.status(400).json({
        success: false,
        error: "Missing required fields: deviceId and name are required"
      });
    }
    if (typeof deviceId !== 'string' || typeof name !== 'string') {
      return res.status(400).json({ success: false, error: "Invalid input types" });
    }
    if (deviceId.length > 128) {
      return res.status(400).json({ success: false, error: "deviceId too long" });
    }
    if (name.length > 128) {
      return res.status(400).json({ success: false, error: "Device name too long" });
    }
    if (token !== undefined && (typeof token !== 'string' || token.length > 256)) {
      return res.status(400).json({ success: false, error: "Invalid token format" });
    }
    console.log("🔍 Step 1: Checking for exact deviceId match...");
    const exactMatch = await db.select().from(devices).where(eq(devices.deviceId, deviceId)).limit(1);
    if (exactMatch.length > 0) {
      console.log("✅ Exact match found! Re-pairing existing device...");
      const newPairingToken = crypto.randomBytes(32).toString("hex");
      console.log("🔑 Generated new pairing token for reconnection");
      await db.update(devices).set({
        name,
        model: model || null,
        androidVersion: osVersion || null,
        pairingToken: newPairingToken,
        // ✅ Update with new token
        isConnected: true,
        lastSeen: /* @__PURE__ */ new Date(),
        storageTotal: storageTotal || null,
        storageUsed: storageUsed || null,
        updatedAt: /* @__PURE__ */ new Date()
      }).where(eq(devices.deviceId, deviceId));
      const updatedDevice = await db.select().from(devices).where(eq(devices.deviceId, deviceId)).limit(1);
      console.log("✅ Device re-paired successfully (exact match):", updatedDevice[0].id);
      return res.status(200).json({
        success: true,
        device: updatedDevice[0],
        message: "Welcome back! Device reconnected successfully.",
        reconnected: true
      });
    }
    console.log("🔍 Step 2: Checking for hardware fingerprint match...");
    const fingerprint = createDeviceFingerprint(name, model, platform);
    console.log("🔑 Device fingerprint:", fingerprint);
    const allDevices = await db.select().from(devices);
    let hardwareMatch = null;
    for (const device of allDevices) {
      const existingFingerprint = createDeviceFingerprint(
        device.name,
        device.model || void 0,
        platform
        // Use current platform since it's not stored in old schema
      );
      if (existingFingerprint === fingerprint) {
        hardwareMatch = device;
        console.log("✅ Hardware match found! Device ID:", device.id);
        break;
      }
    }
    if (hardwareMatch) {
      console.log("🔄 Reconnecting device after app reinstall/factory reset...");
      const newPairingToken = crypto.randomBytes(32).toString("hex");
      console.log("🔑 Generated new pairing token for hardware match reconnection");
      await db.update(devices).set({
        deviceId,
        // Update to new UUID from fresh install
        name,
        model: model || null,
        androidVersion: osVersion || null,
        pairingToken: newPairingToken,
        // ✅ Update with new token
        isConnected: true,
        lastSeen: /* @__PURE__ */ new Date(),
        storageTotal: storageTotal || null,
        storageUsed: storageUsed || null,
        updatedAt: /* @__PURE__ */ new Date()
      }).where(eq(devices.id, hardwareMatch.id));
      const reconnectedDevice = await db.select().from(devices).where(eq(devices.id, hardwareMatch.id)).limit(1);
      console.log("✅ Device reconnected successfully (hardware match):", reconnectedDevice[0].id);
      return res.status(200).json({
        success: true,
        device: reconnectedDevice[0],
        message: "Device recognized! Your backups are ready to sync.",
        reconnected: true
      });
    }
    console.log("🆕 Step 3: New device detected - validating token...");
    if (!token) {
      console.log("❌ Missing token for new device");
      return res.status(400).json({
        success: false,
        error: "Pairing token required for new devices. Please scan the QR code from your dashboard."
      });
    }
    const validator = await getTokenValidator();
    if (validator) {
      const isValid = validator(token);
      console.log("🔐 Token validation result:", isValid);
      if (!isValid) {
        console.log("❌ Token validation failed");
        return res.status(401).json({
          success: false,
          error: "Invalid or expired pairing token. Please generate a new QR code."
        });
      }
    } else {
      console.log("⚠️  Token validator not available, skipping validation");
    }
    const pairingToken = crypto.randomBytes(32).toString("hex");
    console.log("➕ Creating new device...");
    const result = await db.insert(devices).values({
      deviceId,
      name,
      model: model || null,
      androidVersion: osVersion || null,
      pairingToken,
      isConnected: true,
      lastSeen: /* @__PURE__ */ new Date(),
      storageTotal: storageTotal || null,
      storageUsed: storageUsed || null
    });
    const insertId = Number(result[0].insertId);
    const newDevice = await db.select().from(devices).where(eq(devices.id, insertId)).limit(1);
    if (newDevice.length === 0) {
      console.log("❌ Failed to retrieve created device");
      return res.status(500).json({
        success: false,
        error: "Failed to retrieve created device"
      });
    }
    console.log("✅ New device paired successfully:", newDevice[0].id);
    res.status(201).json({
      success: true,
      device: newDevice[0],
      message: "Device paired successfully! Your backups will start automatically.",
      reconnected: false
    });
  } catch (error) {
    console.error("❌ Device pairing error:", error);
    res.status(500).json({
      success: false,
      error: "Failed to pair device",
      message: String(error)
    });
  }
}

export { handler as h };
