export const dynamic = 'force-dynamic';

import { NextRequest, NextResponse } from 'next/server';
import { getServerSession } from 'next-auth';
import { authOptions } from '@/lib/auth/auth-options';
import { prisma } from '@/lib/db';
import { auditLogger } from '@/lib/autonomy/audit-logger';

/**
 * GET /api/backups/schedule - Get backup schedule config
 */
export async function GET() {
  try {
    const session = await getServerSession(authOptions);
    if (!session?.user?.roles?.includes('admin')) {
      return NextResponse.json({ error: 'Admin access required' }, { status: 403 });
    }

    let schedule = await prisma.backupSchedule.findFirst();

    // Create default schedule if none exists
    if (!schedule) {
      schedule = await prisma.backupSchedule.create({
        data: {
          name: 'Default Schedule',
          frequency: 'DAILY',
          retentionDays: 30,
          entityTypes: [],
          enabled: false,
        },
      });
    }

    return NextResponse.json({ schedule });
  } catch (err: any) {
    console.error('GET /api/backups/schedule error:', err);
    return NextResponse.json({ error: err.message }, { status: 500 });
  }
}

/**
 * PUT /api/backups/schedule - Update backup schedule config
 */
export async function PUT(req: NextRequest) {
  try {
    const session = await getServerSession(authOptions);
    if (!session?.user?.roles?.includes('admin')) {
      return NextResponse.json({ error: 'Admin access required' }, { status: 403 });
    }

    const body = await req.json();
    const { frequency, retentionDays, entityTypes, enabled, name } = body;

    let schedule = await prisma.backupSchedule.findFirst();

    const previousState = schedule ? { ...schedule } : null;

    const data: any = {};
    if (name !== undefined) data.name = name;
    if (frequency !== undefined) data.frequency = frequency;
    if (retentionDays !== undefined) data.retentionDays = retentionDays;
    if (entityTypes !== undefined) data.entityTypes = entityTypes;
    if (enabled !== undefined) data.enabled = enabled;

    // Calculate next run time
    if (enabled && frequency) {
      const now = new Date();
      switch (frequency) {
        case 'HOURLY':
          data.nextRunAt = new Date(now.getTime() + 60 * 60 * 1000);
          break;
        case 'DAILY':
          data.nextRunAt = new Date(now.getTime() + 24 * 60 * 60 * 1000);
          break;
        case 'WEEKLY':
          data.nextRunAt = new Date(now.getTime() + 7 * 24 * 60 * 60 * 1000);
          break;
      }
    }

    if (schedule) {
      schedule = await prisma.backupSchedule.update({
        where: { id: schedule.id },
        data,
      });
    } else {
      schedule = await prisma.backupSchedule.create({
        data: {
          name: name || 'Default Schedule',
          frequency: frequency || 'DAILY',
          retentionDays: retentionDays || 30,
          entityTypes: entityTypes || [],
          enabled: enabled || false,
          ...data,
        },
      });
    }

    // Audit log the config change
    auditLogger.setContext({ userId: session.user.id });
    await auditLogger.logConfigChange(
      'config',
      schedule.id,
      previousState || {},
      schedule as any,
      `Backup schedule updated by ${session.user.name || session.user.email}`,
    );
    auditLogger.clearContext();

    return NextResponse.json({ schedule });
  } catch (err: any) {
    console.error('PUT /api/backups/schedule error:', err);
    return NextResponse.json({ error: err.message }, { status: 500 });
  }
}
