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

export async function GET(request: NextRequest) {
  try {
    const authHeader = request.headers.get('authorization');
    const cronSecret = process.env.CRON_SECRET || 'development-secret';
    
    if (authHeader !== `Bearer ${cronSecret}`) {
      return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
    }

    const locations = await prisma.location.findMany({
      where: {
        active: true,
        emailSyncEnabled: true,
      },
    });

    const results: any[] = [];

    for (const location of locations) {
      try {
        const result = await emailSyncService.syncLocationEmails(location.id);
        results.push({
          locationId: location.id,
          locationName: location.name,
          ...result,
        });
      } catch (error: any) {
        results.push({
          locationId: location.id,
          locationName: location.name,
          success: false,
          newEmails: 0,
          newBookings: 0,
          errors: [error.message],
        });
      }
    }

    const summary = {
      totalLocations: locations.length,
      totalEmails: results.reduce((sum, r) => sum + (r.newEmails || 0), 0),
      totalBookings: results.reduce((sum, r) => sum + (r.newBookings || 0), 0),
      results,
    };

    console.log('Cron email sync completed:', summary);

    return NextResponse.json(summary);
  } catch (error: any) {
    console.error('Cron email sync error:', error);
    return NextResponse.json(
      { error: error.message || 'Internal server error' },
      { status: 500 }
    );
  }
}
