import { getSession } from '@/lib/auth';
import { performAutomaticBackup } from '@/lib/backup-actions';
import { NextResponse } from 'next/server';

export const dynamic = 'force-dynamic';

/**
 * POST /api/admin/backup
 * 
 * Manually trigger an automatic backup
 * Admin session required
 * No password required
 */
export async function POST() {
  try {
    const session = await getSession();
    if (!session?.user || session.user.role !== 'admin') {
      return NextResponse.json(
        { success: false, error: 'Unauthorized' },
        { status: 401 }
      );
    }

    const result = await performAutomaticBackup();

    if (!result.success) {
      return NextResponse.json(
        { success: false, error: result.error || 'Backup failed' },
        { status: 400 }
      );
    }

    return NextResponse.json({
      success: true,
      backupId: result.backupId,
      backupPath: result.backupPath,
      message: 'Automatic backup triggered successfully',
    }, { status: 200 });
  } catch (error: any) {
    console.error('Auto-backup API error:', error);
    return NextResponse.json(
      { success: false, error: error?.message || 'Failed to trigger backup' },
      { status: 500 }
    );
  }
}
