import { d as db } from '../create-upload-progress-table/POST-C-OoiMoW.js';
import { sql } from 'drizzle-orm';
import fs from 'fs';
import path from 'path';
import { fileURLToPath } from 'url';

const __filename$1 = fileURLToPath(import.meta.url);
const __dirname$1 = path.dirname(__filename$1);
async function handler(req, res) {
  // Guard 1: only allow requests originating from localhost
  const remoteAddr = req.ip || req.socket?.remoteAddress || '';
  const isLocal = remoteAddr === '127.0.0.1' || remoteAddr === '::1' || remoteAddr === '::ffff:127.0.0.1';
  if (!isLocal) {
    console.warn(`[Database Reset] Blocked remote request from ${remoteAddr}`);
    return res.status(403).json({ success: false, error: "Forbidden: admin operations are restricted to localhost" });
  }

  // Guard 2: require ADMIN_KEY header to match env var (set a strong value in .env)
  const adminKey = process.env.ADMIN_KEY;
  if (adminKey) {
    const providedKey = req.headers['x-admin-key'];
    if (!providedKey || providedKey !== adminKey) {
      console.warn('[Database Reset] Blocked request with missing or invalid x-admin-key header');
      return res.status(401).json({ success: false, error: "Unauthorized: valid x-admin-key header required" });
    }
  } else {
    console.warn('[Database Reset] WARNING: ADMIN_KEY env var not set - add it to .env to secure this endpoint');
  }

  try {
    console.log("[Database Reset] Starting database reset...");
    const [tables] = await db.execute(sql`SHOW TABLES`);
    console.log(`[Database Reset] Found ${tables.length} tables to drop`);
    for (const table of tables) {
      const tableName = Object.values(table)[0];
      console.log(`[Database Reset] Dropping table: ${tableName}`);
      await db.execute(sql.raw(`DROP TABLE IF EXISTS \`${tableName}\``));
    }
    console.log("[Database Reset] All tables dropped");
    const migrationsDir = path.join(__dirname$1, "../../../../../drizzle");
    const migrationFiles = [
      "0000_fancy_junta.sql",
      "0001_uneven_robin_chapel.sql",
      "0002_blue_next_avengers.sql",
      "0003_add_encryption_fields.sql",
      "0004_add_verification_fields.sql",
      "0005_add_storage_config.sql",
      "0006_add_backup_schedules.sql",
      "0007_add_compression_fields.sql",
      "0008_add_upload_progress.sql",
      "0009_add_admin_users.sql"
    ];
    for (const file of migrationFiles) {
      const filePath = path.join(migrationsDir, file);
      if (fs.existsSync(filePath)) {
        console.log(`[Database Reset] Running migration: ${file}`);
        const sqlContent = fs.readFileSync(filePath, "utf-8");
        const statements = sqlContent.split("\n").filter((line) => !line.trim().startsWith("--")).join("\n").split(";").map((s) => s.trim()).filter((s) => s.length > 0);
        for (const statement of statements) {
          try {
            await db.execute(sql.raw(statement));
          } catch (error) {
            console.error(`[Database Reset] Error in ${file}:`, error.message);
            throw error;
          }
        }
        console.log(`[Database Reset] ✓ ${file} completed`);
      }
    }
    const [newTables] = await db.execute(sql`SHOW TABLES`);
    console.log(`[Database Reset] ✓ Database reset complete with ${newTables.length} tables`);
    res.json({
      success: true,
      message: "Database reset successfully",
      tablesCreated: newTables.length
    });
  } catch (error) {
    console.error("[Database Reset] Failed:", error);
    res.status(500).json({
      success: false,
      error: "Failed to reset database",
      message: error.message
    });
  }
}

export { handler as h };
