const db = require('../models');
const fs = require('fs');
const path = require('path');

const createEmployerProfile = async (req, res, next) => {
    try {
        let profile = await db.EmployerProfile.findOne({ where: { userId: req.user.id } });
        
        if (profile) {
            profile = await profile.update(req.body);
            return res.json(profile);
        }

        profile = await db.EmployerProfile.create({
            userId: req.user.id,
            ...req.body
        });
        res.status(201).json(profile);
    } catch (error) {
        next(error);
    }
};

const createJobSeekerProfile = async (req, res, next) => {
    try {
        let profile = await db.JobSeekerProfile.findOne({ where: { userId: req.user.id } });
        
        // Handle File Path & Cleanup
        let cvUrl = profile ? profile.cvUrl : null;

        if (req.file) {
            // If a new file is uploaded
            const newCvUrl = req.file.path.replace(/\\/g, "/");

            // Check if there was an old file and delete it
            if (profile && profile.cvUrl) {
                const oldPath = path.join(__dirname, '..', profile.cvUrl); // Adjust based on your root struct
                
                // Check if file exists before trying to delete
                if (fs.existsSync(oldPath)) {
                    try {
                        fs.unlinkSync(oldPath);
                        console.log(`Deleted old CV: ${oldPath}`);
                    } catch (err) {
                        console.error(`Failed to delete old CV: ${oldPath}`, err);
                        // We proceed even if delete fails, to not block the update
                    }
                }
            }
            
            cvUrl = newCvUrl;
        }
        
        // Handle Structured Data
        let structuredProfileData = {};
        if (req.body.structuredProfileData) {
            if (typeof req.body.structuredProfileData === 'string') {
                try {
                    structuredProfileData = JSON.parse(req.body.structuredProfileData);
                } catch (e) {
                    console.error("JSON Parse Error", e);
                }
            } else {
                structuredProfileData = req.body.structuredProfileData;
            }
        } else if (profile) {
            structuredProfileData = profile.structuredProfileData;
        }

        if (profile) {
            // Update existing
            await profile.update({
                fullName: req.body.fullName || profile.fullName,
                cvUrl: cvUrl,
                structuredProfileData: structuredProfileData
            });
        } else {
            // Create new
            profile = await db.JobSeekerProfile.create({
                userId: req.user.id,
                fullName: req.body.fullName,
                cvUrl: cvUrl,
                structuredProfileData: structuredProfileData
            });
        }
        
        res.status(201).json(profile);
    } catch (error) {
        next(error);
    }
};

const getMyProfile = async (req, res, next) => {
    try {
        let profile;
        if (req.user.role === 'Employer') {
            profile = await db.EmployerProfile.findOne({ where: { userId: req.user.id } });
        } else if (req.user.role === 'Job Seeker') {
            profile = await db.JobSeekerProfile.findOne({ where: { userId: req.user.id } });
        } else if (req.user.role === 'Admin') {
            return res.json({ user: req.user, role: 'Admin' });
        }
        
        if (!profile) return res.status(404).json({ message: 'Profile not found' });
        
        const response = profile.toJSON();
        response.user = req.user; 
        
        res.json(response);
    } catch (error) {
        next(error);
    }
};

module.exports = { createEmployerProfile, createJobSeekerProfile, getMyProfile };