const db = require('../models');
// FIX: Changed '../utils/emailService' to '../utils/emailServices' to match actual filename
const sendEmail = require('../utils/emailServices'); 

const applyForJob = async (req, res, next) => {
    try {
        const seekerProfile = await db.JobSeekerProfile.findOne({ where: { userId: req.user.id } });
        if (!seekerProfile) return res.status(404).json({ message: 'Please create your profile before applying.' });

        const { jobId } = req.params;

        const existingApplication = await db.Application.findOne({
            where: { jobId, jobSeekerProfileId: seekerProfile.id }
        });

        if (existingApplication) return res.status(400).json({ message: 'You have already applied for this job.' });

        await db.Application.create({
            jobId,
            jobSeekerProfileId: seekerProfile.id,
            status: 'New'
        });

        res.status(201).json({ message: 'Application submitted successfully' });
    } catch (error) {
        next(error);
    }
};

const getJobApplicants = async (req, res, next) => {
    try {
        const { jobId } = req.params;
        const employerProfile = await db.EmployerProfile.findOne({ where: { userId: req.user.id } });
        
        const job = await db.Job.findOne({ where: { id: jobId, employerProfileId: employerProfile.id } });
        if (!job) return res.status(403).json({ message: 'Not authorized to view these applicants' });

        const applications = await db.Application.findAll({
            where: { jobId },
            include: [{ 
                model: db.JobSeekerProfile, 
                as: 'jobSeeker',
                include: [{
                    model: db.User,
                    as: 'user',
                    attributes: ['email']
                }]
            }]
        });

        res.json(applications);
    } catch (error) {
        next(error);
    }
};

const getMyApplications = async (req, res, next) => {
    try {
        const seekerProfile = await db.JobSeekerProfile.findOne({ where: { userId: req.user.id } });
        if (!seekerProfile) return res.json([]); 

        const applications = await db.Application.findAll({
            where: { jobSeekerProfileId: seekerProfile.id },
            include: [{ 
                model: db.Job, 
                as: 'job',
                include: [{
                    model: db.EmployerProfile,
                    as: 'employer',
                    attributes: ['companyName']
                }]
            }],
            order: [['createdAt', 'DESC']]
        });

        res.json(applications);
    } catch (error) {
        next(error);
    }
};

const sendApplicantEmail = async (req, res, next) => {
    try {
        const { applicationId } = req.params;
        const { subject, body, type } = req.body; 
        const employerProfile = await db.EmployerProfile.findOne({ where: { userId: req.user.id } });

        const application = await db.Application.findByPk(applicationId, {
            include: [
                { model: db.Job, as: 'job' },
                { 
                    model: db.JobSeekerProfile, 
                    as: 'jobSeeker', 
                    include: [{ model: db.User, as: 'user' }] 
                }
            ]
        });

        if (!application) return res.status(404).json({ message: 'Application not found' });
        
        if (application.job.employerProfileId !== employerProfile.id) {
            return res.status(403).json({ message: 'Not authorized' });
        }

        // Get email from nested User object
        const applicantEmail = application.jobSeeker?.user?.email; 

        if (!applicantEmail) {
            return res.status(400).json({ message: 'Applicant email not found.' });
        }
        
        const htmlBody = body.replace(/\n/g, '<br>');
        
        await sendEmail(applicantEmail, subject, htmlBody);
        
        // Auto-update status logic
        let newStatus = null;
        if (type === 'Shortlisted') newStatus = 'Shortlisted';
        else if (type === 'Interview') newStatus = 'Interviewing';
        else if (type === 'Rejected') newStatus = 'Rejected';

        if (newStatus) {
            await application.update({ status: newStatus });
        }

        res.json({ message: 'Email sent successfully', success: true });

    } catch (error) {
        next(error);
    }
};

const updateApplicationStatus = async (req, res, next) => {
    try {
        const { applicationId } = req.params;
        const { status } = req.body;
        const employerProfile = await db.EmployerProfile.findOne({ where: { userId: req.user.id } });

        const application = await db.Application.findByPk(applicationId, {
            include: [{ model: db.Job, as: 'job' }]
        });

        if (!application) return res.status(404).json({ message: 'Application not found' });
        
        if (application.job.employerProfileId !== employerProfile.id) {
            return res.status(403).json({ message: 'Not authorized' });
        }

        if (status === 'Hired') {
            await application.update({ status: 'Hired' });
            await application.job.update({ status: 'Filled' });

            const transaction = await db.Transaction.create({
                employerProfileId: employerProfile.id,
                jobId: application.job.id,
                amount: 50.00,
                status: 'Pending',
                paymentGatewayRefId: `PAY-${Date.now()}`
            });

            return res.json({ 
                message: 'Applicant marked as Hired.',
                paymentUrl: `http://localhost:3000/payment-success?txn=${transaction.id}`, 
                transactionId: transaction.id
            });
        }

        await application.update({ status });
        res.json({ message: `Application status updated to ${status}` });

    } catch (error) {
        next(error);
    }
};

module.exports = { applyForJob, getJobApplicants, getMyApplications, sendApplicantEmail, updateApplicationStatus };