import { NextRequest, NextResponse } from 'next/server';
import { backupService } from '@/services/data-management/backup';

interface RouteParams {
  params: Promise<{
    filename: string;
  }>;
}

export async function DELETE(request: NextRequest, { params }: RouteParams) {
  try {
    const { filename } = await params;

    // Vérification de sécurité - s'assurer que c'est bien un fichier de backup
    if (
      !filename.startsWith('towercontrol_') ||
      (!filename.endsWith('.db') && !filename.endsWith('.db.gz'))
    ) {
      return NextResponse.json(
        { success: false, error: 'Invalid backup filename' },
        { status: 400 }
      );
    }

    await backupService.deleteBackup(filename);

    return NextResponse.json({
      success: true,
      message: `Backup ${filename} deleted successfully`,
    });
  } catch (error) {
    console.error('Error deleting backup:', error);
    return NextResponse.json(
      {
        success: false,
        error:
          error instanceof Error ? error.message : 'Failed to delete backup',
      },
      { status: 500 }
    );
  }
}

export async function POST(request: NextRequest, { params }: RouteParams) {
  try {
    const { filename } = await params;
    const body = await request.json();
    const { action } = body;

    if (action === 'restore') {
      // Vérification de sécurité
      if (
        !filename.startsWith('towercontrol_') ||
        (!filename.endsWith('.db') && !filename.endsWith('.db.gz'))
      ) {
        return NextResponse.json(
          { success: false, error: 'Invalid backup filename' },
          { status: 400 }
        );
      }

      // Protection environnement de production
      if (process.env.NODE_ENV === 'production') {
        return NextResponse.json(
          {
            success: false,
            error: 'Restore not allowed in production via API',
          },
          { status: 403 }
        );
      }

      await backupService.restoreBackup(filename);

      return NextResponse.json({
        success: true,
        message: `Database restored from ${filename}`,
      });
    }

    return NextResponse.json(
      { success: false, error: 'Invalid action' },
      { status: 400 }
    );
  } catch (error) {
    console.error('Error in backup operation:', error);
    return NextResponse.json(
      {
        success: false,
        error: error instanceof Error ? error.message : 'Operation failed',
      },
      { status: 500 }
    );
  }
}
