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

export async function GET(request: NextRequest) {
  try {
    const { searchParams } = new URL(request.url);
    const action = searchParams.get('action');

    if (action === 'logs') {
      const maxLines = parseInt(searchParams.get('maxLines') || '100');
      const logs = await backupService.getBackupLogs(maxLines);

      return NextResponse.json({
        success: true,
        data: { logs },
      });
    }

    if (action === 'stats') {
      const days = parseInt(searchParams.get('days') || '30');
      const stats = await backupService.getBackupStats(days);

      return NextResponse.json({
        success: true,
        data: stats,
      });
    }

    console.log('🔄 API GET /api/backups called');

    // Test de la configuration d'abord
    const config = await backupService.getConfig();
    console.log('✅ Config loaded:', config);

    // Test du scheduler
    const schedulerStatus = backupScheduler.getStatus();
    console.log('✅ Scheduler status:', schedulerStatus);

    // Test de la liste des backups
    const backups = await backupService.listBackups();
    console.log('✅ Backups loaded:', backups.length);

    const response = {
      success: true,
      data: {
        backups,
        scheduler: schedulerStatus,
        config,
      },
    };

    console.log('✅ API response ready');
    return NextResponse.json(response);
  } catch (error) {
    console.error('❌ Error fetching backups:', error);
    console.error(
      'Error stack:',
      error instanceof Error ? error.stack : 'Unknown'
    );

    return NextResponse.json(
      {
        success: false,
        error:
          error instanceof Error ? error.message : 'Failed to fetch backups',
        details: error instanceof Error ? error.stack : undefined,
      },
      { status: 500 }
    );
  }
}

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

    switch (action) {
      case 'create':
        const forceCreate = params.force === true;
        const backup = await backupService.createBackup('manual', forceCreate);

        if (backup === null) {
          return NextResponse.json({
            success: true,
            skipped: true,
            message:
              'No changes detected since last backup. Use force=true to create anyway.',
          });
        }

        return NextResponse.json({ success: true, data: backup });

      case 'verify':
        await backupService.verifyDatabaseHealth();
        return NextResponse.json({
          success: true,
          message: 'Database health check passed',
        });

      case 'config':
        await backupService.updateConfig(params.config);
        // Redémarrer le scheduler si la config a changé
        if (
          params.config.enabled !== undefined ||
          params.config.interval !== undefined
        ) {
          backupScheduler.restart();
        }
        return NextResponse.json({
          success: true,
          message: 'Configuration updated',
          data: await backupService.getConfig(),
        });

      case 'scheduler':
        if (params.enabled) {
          backupScheduler.start();
        } else {
          backupScheduler.stop();
        }
        return NextResponse.json({
          success: true,
          data: backupScheduler.getStatus(),
        });

      default:
        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 : 'Unknown error',
      },
      { status: 500 }
    );
  }
}
