export const dynamic = 'force-dynamic';

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

/**
 * POST /api/backups/[id]/restore - Restore from a backup
 * 
 * Requires 3x verification: the request body must include
 * `confirmations` array with exactly 3 confirmation tokens.
 * Each confirmation represents a deliberate user action in the UI.
 */
export async function POST(req: NextRequest, { params }: { params: { id: string } }) {
  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 { confirmations, entityTypes, entityIds } = body;

    // Validate 3x confirmation
    if (!Array.isArray(confirmations) || confirmations.length !== 3) {
      return NextResponse.json(
        { error: 'Restore requires exactly 3 confirmations. This is a safety measure.' },
        { status: 400 }
      );
    }

    // Each confirmation must be a non-empty string with a timestamp
    for (let i = 0; i < 3; i++) {
      const c = confirmations[i];
      if (!c || typeof c !== 'object' || !c.confirmed || !c.timestamp) {
        return NextResponse.json(
          { error: `Confirmation ${i + 1} is invalid. Each confirmation must include confirmed=true and a timestamp.` },
          { status: 400 }
        );
      }
    }

    // Log the restore attempt with all 3 confirmations
    auditLogger.setContext({ userId: session.user.id });
    await auditLogger.log({
      action: 'import',
      resource: 'system',
      resourceId: params.id,
      description: `Restore initiated by ${session.user.name || session.user.email} with 3x verification`,
      metadata: {
        confirmations: confirmations.map((c: any, i: number) => ({
          step: i + 1,
          timestamp: c.timestamp,
          reason: c.reason || 'N/A',
        })),
        entityTypes,
        entityIds,
      },
    });
    auditLogger.clearContext();

    const result = await restoreFromBackup({
      backupId: params.id,
      entityTypes,
      entityIds,
      performedById: session.user.id,
    });

    return NextResponse.json(result);
  } catch (err: any) {
    console.error('POST /api/backups/[id]/restore error:', err);
    return NextResponse.json({ error: err.message }, { status: 500 });
  }
}
