import { NextResponse } from 'next/server';
import prisma from '@/lib/prisma';
import { EmailQueueService } from '@/services/EmailQueueService';

/**
 * Cron Job: Process Job Alerts for Candidates
 * Handles daily and weekly digests. Instant alerts are triggered separately.
 * GET /api/cron/job-alerts
 */
export async function GET(request: Request) {
    try {
        const authHeader = request.headers.get('authorization');
        if (process.env.CRON_SECRET && authHeader !== `Bearer ${process.env.CRON_SECRET}`) {
            return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
        }

        const now = new Date();
        const oneDayAgo = new Date(now.getTime() - 24 * 60 * 60 * 1000);
        const oneWeekAgo = new Date(now.getTime() - 7 * 24 * 60 * 60 * 1000);

        // 1. Find active alerts that are due for processing
        const alertsToProcess = await prisma.savedSearch.findMany({
            where: {
                is_active: true,
                alert_frequency: { in: ['daily', 'weekly'] },
                OR: [
                    { paused_until: null },
                    { paused_until: { lt: now } }
                ],
                AND: [
                    {
                        OR: [
                            { alert_frequency: 'daily', last_checked_at: { lt: oneDayAgo } },
                            { alert_frequency: 'weekly', last_checked_at: { lt: oneWeekAgo } }
                        ]
                    }
                ]
            },
            include: {
                user: {
                    select: {
                        id: true,
                        email: true,
                        name: true,
                        is_active: true,
                        skills: { include: { skill: true } },
                        email_preference: true
                    }
                }
            }
        });

        let emailsQueued = 0;
        let alertsProcessed = 0;
        let errors = 0;

        for (const alert of alertsToProcess) {
            if (!alert.user.is_active) continue;

            // Check email preferences
            const prefs = alert.user.email_preference;
            if (prefs?.unsubscribed_all) continue;
            if (prefs?.global_pause_until && new Date(prefs.global_pause_until) > now) continue;

            const filters = alert.filters as Record<string, any>;

            try {
                // Build WHERE clause from saved filters
                const whereClause: any = {
                    status: 'published',
                    posted_at: { gt: alert.last_checked_at }
                };

                if (filters.q) {
                    whereClause.OR = [
                        { title: { contains: filters.q, mode: 'insensitive' } },
                        { company: { contains: filters.q, mode: 'insensitive' } },
                        { description: { contains: filters.q, mode: 'insensitive' } }
                    ];
                }
                if (filters.l) {
                    whereClause.city = { contains: filters.l, mode: 'insensitive' };
                }
                if (filters.type) {
                    const types = typeof filters.type === 'string' ? filters.type.split(',') : filters.type;
                    whereClause.type = { in: types };
                }
                if (filters.workLocation) {
                    const locs = typeof filters.workLocation === 'string' ? filters.workLocation.split(',') : filters.workLocation;
                    whereClause.work_location_type = { in: locs };
                }
                if (filters.experience) {
                    const exps = typeof filters.experience === 'string' ? filters.experience.split(',') : filters.experience;
                    whereClause.experience_level = { in: exps };
                }
                if (filters.salaryMin) {
                    whereClause.salary_max = { gte: parseInt(filters.salaryMin) };
                }

                // Fetch matching jobs with skills for scoring
                const matchingJobs = await prisma.job.findMany({
                    where: whereClause,
                    include: {
                        skills: { include: { skill: true } }
                    },
                    take: 50, // Fetch more for scoring, will trim later
                    orderBy: { posted_at: 'desc' }
                });

                if (matchingJobs.length === 0) {
                    await prisma.savedSearch.update({
                        where: { id: alert.id },
                        data: { last_checked_at: now, new_job_count: 0 }
                    });
                    alertsProcessed++;
                    continue;
                }

                // Calculate match scores
                const userSkillNames = alert.user.skills.map(us => us.skill.name.toLowerCase());

                const scoredJobs = matchingJobs.map(job => {
                    const jobSkillNames = job.skills.map(js => js.skill.name.toLowerCase());
                    const matchedSkills = jobSkillNames.filter(s => userSkillNames.includes(s));
                    const skillScore = jobSkillNames.length > 0
                        ? Math.round((matchedSkills.length / jobSkillNames.length) * 100)
                        : 75; // Default score if no skills specified

                    return {
                        id: job.id,
                        title: job.title,
                        company: job.company,
                        city: job.city,
                        state: job.state,
                        salary_min: job.salary_min,
                        salary_max: job.salary_max,
                        currency: job.currency,
                        work_location_type: job.work_location_type,
                        type: job.type,
                        posted_at: job.posted_at,
                        matchScore: skillScore,
                        matchedSkills: matchedSkills.length,
                        totalSkills: jobSkillNames.length
                    };
                })
                .filter(job => job.matchScore >= alert.min_match_score)
                .sort((a, b) => b.matchScore - a.matchScore)
                .slice(0, alert.max_results_per_alert);

                if (scoredJobs.length === 0) {
                    await prisma.savedSearch.update({
                        where: { id: alert.id },
                        data: { last_checked_at: now, new_job_count: 0 }
                    });
                    alertsProcessed++;
                    continue;
                }

                // Record matches for deduplication and analytics
                for (const job of scoredJobs) {
                    await prisma.jobAlertMatch.upsert({
                        where: {
                            saved_search_id_job_id: {
                                saved_search_id: alert.id,
                                job_id: job.id
                            }
                        },
                        update: {
                            match_score: job.matchScore,
                            emailed: true,
                            emailed_at: now
                        },
                        create: {
                            saved_search_id: alert.id,
                            job_id: job.id,
                            match_score: job.matchScore,
                            emailed: true,
                            emailed_at: now
                        }
                    });
                }

                // Queue the alert email
                const baseUrl = process.env.NEXT_PUBLIC_APP_URL || 'http://localhost:3000';
                await EmailQueueService.enqueueEmail(
                    'job_alert',
                    alert.user.email,
                    {
                        alertName: alert.name,
                        recipientName: alert.user.name || 'Job Seeker',
                        frequency: alert.alert_frequency,
                        jobCount: scoredJobs.length,
                        jobs: scoredJobs.map(j => ({
                            title: j.title,
                            company: j.company,
                            location: [j.city, j.state].filter(Boolean).join(', ') || 'Remote',
                            salary: j.salary_min && j.salary_max
                                ? `${j.currency} ${j.salary_min.toLocaleString()} - ${j.salary_max.toLocaleString()}`
                                : j.salary_min ? `${j.currency} ${j.salary_min.toLocaleString()}+` : null,
                            matchScore: j.matchScore,
                            type: j.type,
                            workLocation: j.work_location_type,
                            url: `${baseUrl}/jobs/${j.id}`,
                            applyUrl: `${baseUrl}/jobs/${j.id}/apply`,
                        })),
                        manageUrl: `${baseUrl}/dashboard/settings/email-preferences`,
                        unsubscribeUrl: `${baseUrl}/api/email/unsubscribe?alert=${alert.id}`,
                    },
                    alert.user.id
                );

                emailsQueued++;

                // Update alert tracking
                await prisma.savedSearch.update({
                    where: { id: alert.id },
                    data: {
                        last_checked_at: now,
                        new_job_count: scoredJobs.length
                    }
                });

                alertsProcessed++;

            } catch (err) {
                console.error(`[Cron: job-alerts] Error processing alert ${alert.id}:`, err);
                errors++;
            }
        }

        return NextResponse.json({
            success: true,
            processed: alertsProcessed,
            emailsQueued,
            errors
        });

    } catch (error: any) {
        console.error('[Cron: job-alerts] Fatal error:', error);
        return NextResponse.json({ error: error.message }, { status: 500 });
    }
}
