import { d as db, b as backups } from '../../../admin/create-upload-progress-table/POST-C-OoiMoW.js';
import { eq } from 'drizzle-orm';
import fs from 'fs';
import path from 'path';
import { a as getTempDir } from '../../../auth/setup/POST-DYMc2GPx.js';

async function handler(req, res) {
  try {
    const { backupId } = req.params;
    const { deviceId } = req.query;
    if (!backupId || !deviceId) {
      return res.status(400).json({
        success: false,
        error: "Backup ID and device ID are required"
      });
    }
    const existingBackup = await db.select().from(backups).where(eq(backups.backupId, backupId)).limit(1);
    if (existingBackup.length > 0) {
      return res.json({
        success: true,
        progress: {
          backupId,
          status: "completed",
          percentComplete: 100,
          backup: existingBackup[0]
        }
      });
    }
    const tempDir = path.join(getTempDir(), "chunks", deviceId, backupId);
    if (!fs.existsSync(tempDir)) {
      return res.json({
        success: true,
        progress: {
          backupId,
          status: "uploading",
          chunksReceived: 0,
          percentComplete: 0
        }
      });
    }
    const receivedChunks = fs.readdirSync(tempDir).filter((f) => f.startsWith("chunk_"));
    const metadataPath = path.join(tempDir, "metadata.json");
    let totalChunks = null;
    if (fs.existsSync(metadataPath)) {
      try {
        const metadata = JSON.parse(fs.readFileSync(metadataPath, "utf-8"));
        totalChunks = metadata.totalChunks;
      } catch (e) {
        console.warn("Failed to read metadata:", e);
      }
    }
    const percentComplete = totalChunks ? Math.floor(receivedChunks.length / totalChunks * 100) : null;
    res.json({
      success: true,
      progress: {
        backupId,
        status: "uploading",
        chunksReceived: receivedChunks.length,
        totalChunks,
        percentComplete
      }
    });
  } catch (error) {
    console.error("Progress check error:", error);
    res.status(500).json({
      success: false,
      error: "Failed to check upload progress",
      message: String(error)
    });
  }
}

export { handler as h };
