import { NextResponse } from 'next/server';

import { requireSuperAdmin, withAuth } from '@/lib/api/helpers';
import { parseBody } from '@/lib/api/route-helpers';
import { createAuditLog } from '@/lib/audit';
import { errorResponse } from '@/lib/errors';
import { getSchedule, setSchedule } from '@/lib/services/backup-destinations.service';
import { backupScheduleSchema } from '@/lib/validators/backup-destinations';

export const runtime = 'nodejs';

/** Read the global automated-backup schedule. Super-admin only. */
export const GET = withAuth(async (_req, ctx) => {
  try {
    requireSuperAdmin(ctx, 'admin.backup.schedule.get');
    return NextResponse.json({ data: { schedule: await getSchedule() } });
  } catch (error) {
    return errorResponse(error);
  }
});

/** Set the global automated-backup schedule (off | daily | weekly). Super-admin. */
export const PUT = withAuth(async (req, ctx) => {
  try {
    requireSuperAdmin(ctx, 'admin.backup.schedule.set');
    const { schedule } = await parseBody(req, backupScheduleSchema);
    await setSchedule(schedule, ctx.userId);
    await createAuditLog({
      userId: ctx.userId,
      portId: ctx.portId,
      action: 'update',
      entityType: 'backup_schedule',
      entityId: 'global',
      severity: 'warning',
      metadata: { schedule },
      ipAddress: ctx.ipAddress,
      userAgent: ctx.userAgent,
    });
    return NextResponse.json({ data: { schedule } });
  } catch (error) {
    return errorResponse(error);
  }
});
