import { NextResponse } from 'next/server';
import { prisma } from '@/lib/prisma';
import { EmailQueueService } from '@/services/EmailQueueService';
import { formatDistanceToNow } from 'date-fns';

export async function GET(request: Request) {
    try {
        // Verify cron secret if provided in headers to prevent unauthorized runs
        const authHeader = request.headers.get('authorization');
        if (
            process.env.CRON_SECRET &&
            authHeader !== `Bearer ${process.env.CRON_SECRET}`
        ) {
            return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
        }

        console.log('[Cron: process-applications] Starting batch notification job...');

        // 1. Fetch applications that haven't notified the employer yet
        const unnotifiedApplications = await prisma.application.findMany({
            where: {
                employer_notified: false,
            },
            include: {
                job: {
                    include: {
                        employer: true,
                    }
                },
                candidate: {
                    include: {
                        profile: true,
                        skills: {
                            include: { skill: true }
                        }
                    }
                }
            },
            orderBy: {
                applied_at: 'desc'
            }
        });

        if (unnotifiedApplications.length === 0) {
            console.log('[Cron: process-applications] No new applications to notify.');
            return NextResponse.json({ success: true, processed: 0 });
        }

        // Group by employer -> job
        // structure: { [employerId]: { [jobId]: Application[] } }
        const groups: Record<string, Record<string, typeof unnotifiedApplications>> = {};

        for (const app of unnotifiedApplications) {
            const empId = app.job.employer.id;
            const jobId = app.job.id;

            if (!groups[empId]) groups[empId] = {};
            if (!groups[empId][jobId]) groups[empId][jobId] = [];

            groups[empId][jobId].push(app);
        }

        let emailsQueued = 0;
        const processedApplicationIds: string[] = [];

        // Process each group
        for (const empId in groups) {
            const employerJobs = groups[empId];

            for (const jobId in employerJobs) {
                const apps = employerJobs[jobId];
                const job = apps[0].job;
                const employer = job.employer;

                // Format candidates for email digest
                const candidatesOverview = apps.map((app) => {
                    const profile = app.candidate.profile;

                    // Simple logic for Match Score placeholder 
                    // (Assuming match_score is populated, otherwise fallback)
                    const skillsMatch = Math.round(app.match_score || 0);

                    // Grab current title from experiences if present, otherwise use profile headline
                    const title = profile?.headline || 'No title provided';

                    return {
                        name: app.candidate.name || `${app.candidate.first_name || ''} ${app.candidate.last_name || ''}`.trim(),
                        headline: title,
                        skillsMatch,
                        appliedAgo: formatDistanceToNow(new Date(app.applied_at), { addSuffix: true }),
                        applicationId: app.id,
                    };
                });

                // Enqueue digest email
                const baseUrl = process.env.NEXT_PUBLIC_APP_URL || 'http://localhost:3000';

                await EmailQueueService.enqueueEmail(
                    'employer_new_application_digest',
                    employer.email,
                    {
                        employerName: employer.name || 'Employer',
                        jobTitle: job.title,
                        applicationsCount: apps.length,
                        candidates: candidatesOverview,
                        reviewUrl: `${baseUrl}/dashboard/employer/jobs/${job.id}/applications`,
                    },
                    employer.id
                );

                emailsQueued++;
                processedApplicationIds.push(...apps.map(a => a.id));
            }
        }

        // 3. Mark all processed applications as notified
        if (processedApplicationIds.length > 0) {
            await prisma.application.updateMany({
                where: {
                    id: { in: processedApplicationIds }
                },
                data: {
                    employer_notified: true
                }
            });
            console.log(`[Cron: process-applications] Marked ${processedApplicationIds.length} apps as notified.`);
        }

        return NextResponse.json({
            success: true,
            processedApps: processedApplicationIds.length,
            emailsQueued
        });

    } catch (error: any) {
        console.error('[Cron: process-applications] Error:', error);
        return NextResponse.json(
            { error: 'Internal server error', details: error.message },
            { status: 500 }
        );
    }
}
