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

async function handler(req, res) {
  try {
    const {
      deviceId,
      scheduleName,
      frequency,
      timeOfDay,
      daysOfWeek,
      dayOfMonth,
      customCron,
      backupType = "full",
      conditions
    } = req.body;
    if (!deviceId || !scheduleName || !frequency) {
      return res.status(400).json({
        success: false,
        error: "Missing required fields: deviceId, scheduleName, frequency"
      });
    }
    if (frequency === "weekly" && (!daysOfWeek || daysOfWeek.length === 0)) {
      return res.status(400).json({
        success: false,
        error: "daysOfWeek is required for weekly schedules"
      });
    }
    if (frequency === "monthly" && !dayOfMonth) {
      return res.status(400).json({
        success: false,
        error: "dayOfMonth is required for monthly schedules"
      });
    }
    if (frequency === "custom" && !customCron) {
      return res.status(400).json({
        success: false,
        error: "customCron is required for custom schedules"
      });
    }
    const scheduleId = `schedule_${crypto.randomBytes(16).toString("hex")}`;
    const nextRun = calculateNextRun(frequency, timeOfDay, daysOfWeek, dayOfMonth);
    const result = await db.insert(backupSchedules).values({
      scheduleId,
      deviceId,
      scheduleName,
      frequency,
      timeOfDay,
      daysOfWeek: daysOfWeek ? JSON.stringify(daysOfWeek) : null,
      dayOfMonth,
      customCron,
      backupType,
      enabled: true,
      conditions: conditions ? JSON.stringify(conditions) : null,
      nextRun
    });
    const insertId = Number(result[0].insertId);
    const [schedule] = await db.select().from(backupSchedules).where(eq(backupSchedules.id, insertId)).limit(1);
    res.status(201).json({
      success: true,
      schedule,
      message: "Schedule created successfully"
    });
  } catch (error) {
    console.error("Failed to create schedule:", error);
    res.status(500).json({
      success: false,
      error: "Failed to create schedule",
      message: String(error)
    });
  }
}
function calculateNextRun(frequency, timeOfDay, daysOfWeek, dayOfMonth) {
  const now = /* @__PURE__ */ new Date();
  const next = new Date(now);
  if (timeOfDay) {
    const [hours, minutes] = timeOfDay.split(":").map(Number);
    next.setHours(hours, minutes, 0, 0);
  } else {
    next.setHours(0, 0, 0, 0);
  }
  switch (frequency) {
    case "daily":
      if (next <= now) {
        next.setDate(next.getDate() + 1);
      }
      break;
    case "weekly":
      if (daysOfWeek && daysOfWeek.length > 0) {
        const currentDay = now.getDay();
        const sortedDays = [...daysOfWeek].sort((a, b) => a - b);
        let nextDay = sortedDays.find((day) => day > currentDay);
        if (!nextDay) {
          nextDay = sortedDays[0];
          next.setDate(next.getDate() + (7 - currentDay + nextDay));
        } else {
          next.setDate(next.getDate() + (nextDay - currentDay));
        }
      }
      break;
    case "monthly":
      if (dayOfMonth) {
        next.setDate(dayOfMonth);
        if (next <= now) {
          next.setMonth(next.getMonth() + 1);
        }
      }
      break;
    case "custom":
      next.setDate(next.getDate() + 1);
      break;
  }
  return next;
}

export { handler as h };
