const db = require('../models');
const { Op } = require('sequelize');

const createJob = async (req, res, next) => {
    try {
        const employerProfile = await db.EmployerProfile.findOne({ where: { userId: req.user.id } });
        if (!employerProfile) return res.status(404).json({ message: 'Employer profile not found. Please complete your onboarding.' });

        const job = await db.Job.create({
            employerProfileId: employerProfile.id,
            title: req.body.title,
            description: req.body.description,
            location: req.body.location,
            employmentType: req.body.employmentType,
            // Capture new frontend fields
            salaryRange: req.body.salaryRange,
            requirements: req.body.requirements,
            status: 'Active'
        });
        res.status(201).json(job);
    } catch (error) {
        next(error);
    }
};

const getAllJobs = async (req, res, next) => {
    try {
        const { location, q } = req.query;
        let whereClause = { status: 'Active' };

        if (location) whereClause.location = { [Op.like]: `%${location}%` };
        if (q) {
            whereClause[Op.or] = [
                { title: { [Op.like]: `%${q}%` } },
                { '$employer.companyName$': { [Op.like]: `%${q}%` } }
            ];
        }

        const jobs = await db.Job.findAll({
            where: whereClause,
            include: [{ 
                model: db.EmployerProfile, 
                as: 'employer', 
                attributes: ['companyName', 'logoUrl'] 
            }],
            order: [['createdAt', 'DESC']]
        });
        res.json(jobs);
    } catch (error) {
        next(error);
    }
};

const getJobById = async (req, res, next) => {
    try {
        const job = await db.Job.findByPk(req.params.jobId, {
            include: [{ model: db.EmployerProfile, as: 'employer' }]
        });
        if (!job) return res.status(404).json({ message: 'Job not found' });
        res.json(job);
    } catch (error) {
        next(error);
    }
};

const getMyJobs = async (req, res, next) => {
    try {
        const employerProfile = await db.EmployerProfile.findOne({ where: { userId: req.user.id } });
        if (!employerProfile) return res.status(404).json({ message: 'Employer profile not found' });

        // Frontend Dashboard expects 'applicants' count
        const jobs = await db.Job.findAll({ 
            where: { employerProfileId: employerProfile.id },
            include: [{
                model: db.Application,
                as: 'applications',
                attributes: ['id']
            }],
            order: [['createdAt', 'DESC']]
        });

        // Format response to include applicant count
        const formattedJobs = jobs.map(job => {
            const jobJson = job.toJSON();
            jobJson.applicants = job.applications ? job.applications.length : 0;
            delete jobJson.applications; // cleanup
            return jobJson;
        });

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

module.exports = { createJob, getAllJobs, getJobById, getMyJobs };