// src/controllers/workflowController.js
const db = require('../models');
const Report = db.Report;
const User = db.User;
const Observation = db.Observation;

exports.processReport = async (req, res) => {
    try {
        const { reportId, action } = req.body;
        const currentUserRole = req.userData.role;

        const report = await Report.findByPk(reportId);
        if (!report) return res.status(404).json({ message: "التقرير غير موجود" });

        let newStatus = report.status;

        // منطق سير العمل
        if (currentUserRole === 'section_manager' && report.status === 'pending_section_manager') {
            newStatus = action === 'approve' ? 'pending_dept_manager' : 'rejected';
        } 
        else if (currentUserRole === 'env_manager' && report.status === 'pending_dept_manager') {
            newStatus = action === 'approve' ? 'with_maintenance' : 'pending_section_manager';
        }
        else if (currentUserRole === 'inspector' && report.status === 'maintenance_completed') {
            newStatus = action === 'approve' ? 'completed' : 'with_maintenance';
        }

        if (newStatus === report.status) {
            return res.status(403).json({ message: "لا يوجد إجراء متاح لصلاحياتك الحالية" });
        }

        report.status = newStatus;
        await report.save();
        res.json({ message: "تم التحديث", status: newStatus });

    } catch (error) {
        res.status(500).json({ message: error.message });
    }
};

exports.closeObservation = async (req, res) => {
    try {
        const { observationId, actionTaken } = req.body;
        const observation = await Observation.findByPk(observationId);
        
        observation.status = 'تم التصحيح';
        observation.actionTaken = actionTaken;
        observation.isFixed = true;
        if (req.file) observation.rectifiedImage = `/uploads/${req.file.filename}`;
        
        await observation.save();
        res.json({ message: "تم إغلاق الملاحظة" });
    } catch (error) {
        res.status(500).json({ message: error.message });
    }
};

exports.finishMaintenance = async (req, res) => {
    try {
        const { reportId } = req.body;
        const report = await Report.findByPk(reportId);
        report.status = 'maintenance_completed';
        await report.save();
        res.json({ message: "تم الإرسال للمفتش" });
    } catch (error) {
        res.status(500).json({ message: error.message });
    }
};