import { d as db, s as storageConfig } from '../../admin/create-upload-progress-table/POST-C-OoiMoW.js';
import { eq } from 'drizzle-orm';
import { c as createStorageProvider } from '../../backup/delete/_backupId_/DELETE-CSeC5rJf.js';

async function handler(req, res) {
  try {
    const { storageType, config } = req.body;
    const validTypes = ["local", "s3", "gcs", "azure"];
    if (!validTypes.includes(storageType)) {
      return res.status(400).json({
        success: false,
        error: "Invalid storage type",
        validTypes
      });
    }
    if (!config || typeof config !== "object") {
      return res.status(400).json({
        success: false,
        error: "Configuration object is required"
      });
    }
    try {
      const provider = createStorageProvider({ type: storageType, config });
      await provider.exists("test-connection");
    } catch (error) {
      return res.status(400).json({
        success: false,
        error: "Failed to connect to storage provider",
        message: String(error)
      });
    }
    await db.update(storageConfig).set({ isActive: false }).where(eq(storageConfig.isActive, true));
    const result = await db.insert(storageConfig).values({
      storageType,
      config: JSON.stringify(config),
      isActive: true
    });
    const insertId = Number(result[0].insertId);
    const newConfig = await db.select().from(storageConfig).where(eq(storageConfig.id, insertId)).limit(1);
    res.json({
      success: true,
      message: "Storage configuration updated successfully",
      config: newConfig[0]
    });
  } catch (error) {
    console.error("Error updating storage config:", error);
    res.status(500).json({
      success: false,
      error: "Failed to update storage configuration",
      message: String(error)
    });
  }
}

export { handler as h };
