import { d as db, a as adminUsers } from '../../admin/create-upload-progress-table/POST-C-OoiMoW.js';
import { eq } from 'drizzle-orm';
import bcrypt from 'bcrypt';
import fs from 'fs';
import path from 'path';
import os from 'os';

function getAppDataDir() {
  if (process.env.STORAGE_PATH) {
    return process.env.STORAGE_PATH;
  }
  const isDev = process.env.NODE_ENV !== "production";
  if (isDev) {
    return path.resolve(process.cwd(), "data");
  }
  const platform = os.platform();
  const homeDir = os.homedir();
  switch (platform) {
    case "win32":
      return path.join(process.env.PROGRAMDATA || "C:\\ProgramData", "MyCloudVault");
    case "darwin":
      return path.join(homeDir, "cloudvault-backups");
    case "linux":
    default:
      return path.join(homeDir, "cloudvault-backups");
  }
}
function getBackupsDir() {
  if (process.env.STORAGE_PATH) {
    return process.env.STORAGE_PATH;
  }
  return path.join(getAppDataDir(), "backups");
}
function getTempDir() {
  return path.join(os.tmpdir(), "mycloudvault");
}
function getLogsDir() {
  const isDev = process.env.NODE_ENV !== "production";
  if (isDev) {
    return path.join(getAppDataDir(), "logs");
  }
  const platform = os.platform();
  switch (platform) {
    case "win32":
      return path.join(getAppDataDir(), "logs");
    case "darwin":
    case "linux":
    default:
      return "/var/log/mycloudvault";
  }
}
function ensureDir(dirPath) {
  if (!fs.existsSync(dirPath)) {
    fs.mkdirSync(dirPath, { recursive: true });
  }
}
function getPathInfo() {
  return {
    platform: os.platform(),
    appDataDir: getAppDataDir(),
    backupsDir: getBackupsDir(),
    tempDir: getTempDir(),
    logsDir: getLogsDir(),
    isDevelopment: process.env.NODE_ENV !== "production"
  };
}

const DEFAULT_CONFIG = {
  setupCompleted: false,
  version: "1.0.0",
  adminConfigured: false,
  storageConfigured: false,
  databaseConfigured: false
};
let configCache = null;
function getConfigPath() {
  const pathInfo = getPathInfo();
  return path.join(pathInfo.appDataDir, "setup-config.json");
}
function loadSetupConfig() {
  if (configCache) {
    return configCache;
  }
  const configPath = getConfigPath();
  try {
    if (fs.existsSync(configPath)) {
      const data = fs.readFileSync(configPath, "utf-8");
      configCache = JSON.parse(data);
      return configCache;
    }
  } catch (error) {
    console.error("[Setup State] Failed to load config:", error);
  }
  configCache = { ...DEFAULT_CONFIG };
  return configCache;
}
function saveSetupConfig(config) {
  const configPath = getConfigPath();
  const currentConfig = loadSetupConfig();
  const newConfig = {
    ...currentConfig,
    ...config
  };
  try {
    const dir = path.dirname(configPath);
    if (!fs.existsSync(dir)) {
      fs.mkdirSync(dir, { recursive: true });
    }
    fs.writeFileSync(configPath, JSON.stringify(newConfig, null, 2));
    configCache = newConfig;
    console.log("[Setup State] Configuration saved:", configPath);
  } catch (error) {
    console.error("[Setup State] Failed to save config:", error);
    throw error;
  }
}
function markSetupComplete() {
  saveSetupConfig({
    setupCompleted: true,
    setupCompletedAt: (/* @__PURE__ */ new Date()).toISOString()
  });
}
function resetSetup() {
  saveSetupConfig(DEFAULT_CONFIG);
  console.log("[Setup State] Setup state reset");
}
function updateSetupStep(step, completed) {
  const updates = {};
  if (step === "admin") {
    updates.adminConfigured = completed;
  } else if (step === "storage") {
    updates.storageConfigured = completed;
  } else if (step === "database") {
    updates.databaseConfigured = completed;
  }
  saveSetupConfig(updates);
}

async function handler(req, res) {
  try {
    const { username, email, password, fullName } = req.body;
    if (!username || !email || !password) {
      return res.status(400).json({
        success: false,
        error: "Username, email, and password are required"
      });
    }
    if (typeof username !== 'string' || typeof email !== 'string' || typeof password !== 'string') {
      return res.status(400).json({ success: false, error: "Invalid input types" });
    }
    if (username.length < 3 || username.length > 64) {
      return res.status(400).json({ success: false, error: "Username must be between 3 and 64 characters" });
    }
    if (password.length < 8 || password.length > 256) {
      return res.status(400).json({ success: false, error: "Password must be between 8 and 256 characters" });
    }
    if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) {
      return res.status(400).json({ success: false, error: "Invalid email address" });
    }
    if (fullName !== undefined && (typeof fullName !== 'string' || fullName.length > 128)) {
      return res.status(400).json({ success: false, error: "Full name must be a string of max 128 characters" });
    }
    const existingUsers = await db.select().from(adminUsers).limit(1);
    if (existingUsers.length > 0) {
      return res.status(400).json({
        success: false,
        error: "Admin user already exists. Use login instead."
      });
    }
    const passwordHash = await bcrypt.hash(password, 10);
    const result = await db.insert(adminUsers).values({
      username,
      email,
      passwordHash,
      fullName: fullName || null,
      role: "superadmin",
      // First user is superadmin
      isActive: true
    });
    const insertId = Number(result[0].insertId);
    const newUser = await db.select({
      id: adminUsers.id,
      username: adminUsers.username,
      email: adminUsers.email,
      fullName: adminUsers.fullName,
      role: adminUsers.role
    }).from(adminUsers).where(eq(adminUsers.id, insertId)).limit(1);
    updateSetupStep("admin", true);
    res.json({
      success: true,
      message: "Admin user created successfully",
      user: newUser[0]
    });
  } catch (error) {
    console.error("Failed to create admin user:", error);
    res.status(500).json({
      success: false,
      error: "Failed to create admin user",
      message: String(error)
    });
  }
}

export { getTempDir as a, getPathInfo as b, ensureDir as e, getBackupsDir as g, handler as h, loadSetupConfig as l, markSetupComplete as m, resetSetup as r, updateSetupStep as u };
