import { NextResponse } from 'next/server';
import prisma from '@/lib/prisma';
import { EmailQueueService } from '@/services/EmailQueueService';
import { generateIcs } from '@/lib/email/icsGenerator';
import { addHours, addMinutes, format } from 'date-fns';

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 });
        }

        console.log('[Cron: interview-reminders] Starting reminder job...');
        const now = new Date();
        const results = {
            r24h: 0,
            r1h: 0,
            r15m: 0
        };

        // --- 1. 24 HOUR REMINDERS ---
        const r24Interviews = await prisma.interview.findMany({
            where: {
                status: 'scheduled',
                scheduled_start_datetime: {
                    gt: now,
                    lte: addHours(now, 24)
                },
                audit_logs: {
                    none: { action: 'reminder_24h_sent' }
                }
            },
            include: {
                application: {
                    include: {
                        candidate: true,
                        job: { include: { employer: true } }
                    }
                }
            }
        });

        for (const interview of r24Interviews) {
            await enqueueReminder(interview, '24h');
            await prisma.interviewAuditLog.create({
                data: {
                    interview_id: interview.id,
                    user_id: interview.application.job.employer_id,
                    action: 'reminder_24h_sent'
                }
            });
            results.r24h++;
        }

        // --- 2. 1 HOUR REMINDERS ---
        const r1Interviews = await prisma.interview.findMany({
            where: {
                status: 'scheduled',
                scheduled_start_datetime: {
                    gt: now,
                    lte: addHours(now, 1)
                },
                audit_logs: {
                    none: { action: 'reminder_1h_sent' }
                }
            },
            include: {
                application: {
                    include: {
                        candidate: true,
                        job: { include: { employer: true } }
                    }
                }
            }
        });

        for (const interview of r1Interviews) {
            await enqueueReminder(interview, '1h');
            await prisma.interviewAuditLog.create({
                data: {
                    interview_id: interview.id,
                    user_id: interview.application.job.employer_id,
                    action: 'reminder_1h_sent'
                }
            });
            results.r1h++;
        }

        // --- 3. 15 MINUTE REMINDERS ---
        const r15Interviews = await prisma.interview.findMany({
            where: {
                status: 'scheduled',
                scheduled_start_datetime: {
                    gt: now,
                    lte: addMinutes(now, 15)
                },
                audit_logs: {
                    none: { action: 'reminder_15m_sent' }
                }
            },
            include: {
                application: {
                    include: {
                        candidate: true,
                        job: { include: { employer: true } }
                    }
                }
            }
        });

        for (const interview of r15Interviews) {
            await enqueueReminder(interview, '15m');
            await prisma.interviewAuditLog.create({
                data: {
                    interview_id: interview.id,
                    user_id: interview.application.job.employer_id,
                    action: 'reminder_15m_sent'
                }
            });
            results.r15m++;
        }

        return NextResponse.json({ success: true, results });

    } catch (error: any) {
        console.error('[Cron: interview-reminders] Error:', error);
        return NextResponse.json({ error: error.message }, { status: 500 });
    }
}

async function enqueueReminder(interview: any, reminderType: '24h' | '1h' | '15m') {
    const candidate = interview.application.candidate;
    const job = interview.application.job;
    const employer = job.employer;

    const scheduledAt = new Date(interview.scheduled_start_datetime);
    // Use timezone from interview if available
    const tzLabel = interview.timezone || 'UTC';
    const formattedDate = format(scheduledAt, "EEEE, MMM d 'at' h:mm a") + ` (${tzLabel})`;

    // Generate ICS content
    let attachments = [];
    try {
        const icsContent = await generateIcs({
            title: `Interview: ${job.title} at ${employer.name || 'Proten'}`,
            description: `Scheduled interview for the ${job.title} position.\nType: ${interview.type}\nLink: ${interview.video_conference_link || 'TBD'}`,
            start: scheduledAt,
            duration: { hours: 1, minutes: 0 },
            location: interview.location || interview.video_conference_link || 'Online',
            organizer: { name: employer.name || 'Employer', email: employer.email || 'noreply@protenintl.com' },
            sequence: 1
        });

        attachments.push({
            filename: 'interview-invite.ics',
            content: icsContent,
            contentType: 'text/calendar; charset=utf-8; method=REQUEST'
        });
    } catch (err) {
        console.error('Failed to generate ICS for interview', interview.id, err);
    }

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

    await EmailQueueService.enqueueEmail(
        'interview_reminder',
        candidate.email,
        {
            candidateName: candidate.name || `${candidate.first_name || ''} ${candidate.last_name || ''}`.trim() || 'Candidate',
            jobTitle: job.title,
            companyName: employer.name || 'Company',
            scheduledAt: formattedDate,
            interviewType: interview.type,
            meetingLink: interview.video_conference_link,
            location: interview.location,
            dashboardUrl: `${baseUrl}/dashboard/candidate/applications/${interview.application_id}`,
            reminderType,
            attachments
        },
        candidate.id
    );
}
