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 { createBackup, ALL_ENTITY_TYPES, BACKUP_ENTITY_GROUPS, getBackupStats } from '@/lib/backup/engine';

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

    const { searchParams } = new URL(req.url);
    const type = searchParams.get('type');
    const status = searchParams.get('status');
    const limit = parseInt(searchParams.get('limit') || '20');
    const offset = parseInt(searchParams.get('offset') || '0');
    const statsOnly = searchParams.get('stats') === 'true';

    if (statsOnly) {
      const stats = await getBackupStats();
      return NextResponse.json({
        ...stats,
        entityGroups: BACKUP_ENTITY_GROUPS,
        allEntityTypes: ALL_ENTITY_TYPES,
      });
    }

    const where: any = {};
    if (type) where.type = type;
    if (status) where.status = status;

    const [backups, total] = await Promise.all([
      prisma.backup.findMany({
        where,
        orderBy: { createdAt: 'desc' },
        take: limit,
        skip: offset,
      }),
      prisma.backup.count({ where }),
    ]);

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

/**
 * POST /api/backups - Create a new backup
 */
export async function POST(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 {
      name,
      type = 'SNAPSHOT',
      trigger = 'MANUAL',
      entityTypes,
      notes,
      retentionDays,
    } = body;

    if (!name) {
      return NextResponse.json({ error: 'Backup name is required' }, { status: 400 });
    }

    const result = await createBackup({
      name,
      type,
      trigger,
      entityTypes,
      notes,
      retentionDays,
      createdById: session.user.id,
    });

    return NextResponse.json(result, { status: result.success ? 201 : 500 });
  } catch (err: any) {
    console.error('POST /api/backups error:', err);
    return NextResponse.json({ error: err.message }, { status: 500 });
  }
}
