import { NextRequest, NextResponse } from 'next/server';
import { getServerSession } from 'next-auth';
import { authOptions } from '@/lib/auth';
import { emailSyncService } from '@/lib/email-sync';
import { prisma } from '@/lib/prisma';

export async function POST(request: NextRequest) {
  try {
    const session = await getServerSession(authOptions);

    if (!session || session.user.role !== 'ADMIN') {
      return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
    }

    const { locationId } = await request.json();

    if (locationId) {
      // Sync specific location
      console.log(`🔄 Starte E-Mail-Sync für Location: ${locationId}`);
      const result = await emailSyncService.syncLocationEmails(locationId);
      
      return NextResponse.json({
        success: result.success,
        location: locationId,
        newEmails: result.newEmails,
        newBookings: result.newBookings,
        errors: result.errors,
      });
    } else {
      // Sync all locations
      console.log('🔄 Starte E-Mail-Sync für alle Locations...');
      
      const locations = await prisma.location.findMany({
        where: { emailSyncEnabled: true },
        select: { id: true, name: true },
      });

      const results = [];
      
      for (const location of locations) {
        console.log(`📍 Sync: ${location.name}`);
        const result = await emailSyncService.syncLocationEmails(location.id);
        results.push({
          locationId: location.id,
          locationName: location.name,
          ...result,
        });
      }

      const totalNewEmails = results.reduce((sum, r) => sum + r.newEmails, 0);
      const totalNewBookings = results.reduce((sum, r) => sum + r.newBookings, 0);

      return NextResponse.json({
        success: true,
        totalLocations: locations.length,
        totalNewEmails,
        totalNewBookings,
        results,
      });
    }
  } catch (error: any) {
    console.error('❌ E-Mail-Sync Fehler:', error);
    return NextResponse.json(
      { error: error.message || 'E-Mail-Sync fehlgeschlagen' },
      { status: 500 }
    );
  }
}

export async function GET(request: NextRequest) {
  try {
    const session = await getServerSession(authOptions);

    if (!session || session.user.role !== 'ADMIN') {
      return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
    }

    // Get sync status for all locations
    const locations = await prisma.location.findMany({
      select: {
        id: true,
        name: true,
        slug: true,
        emailSyncEnabled: true,
        lastEmailSync: true,
        imapHost: true,
        imapUser: true,
      },
    });

    const status = locations.map(loc => ({
      id: loc.id,
      name: loc.name,
      slug: loc.slug,
      syncEnabled: loc.emailSyncEnabled,
      configured: !!(loc.imapHost && loc.imapUser),
      lastSync: loc.lastEmailSync,
    }));

    return NextResponse.json({ locations: status });
  } catch (error: any) {
    console.error('❌ Fehler beim Abrufen des Sync-Status:', error);
    return NextResponse.json(
      { error: error.message || 'Fehler beim Abrufen des Status' },
      { status: 500 }
    );
  }
}
