// src/controllers/reportController.js
// لاحظ: نستدعي db ثم نأخذ الجداول منه
const db = require('../models');
const Report = db.Report;
const Observation = db.Observation;
const User = db.User;

// 1. إنشاء تقرير جديد
exports.createReport = async (req, res) => {
    try {
        const facilityName = req.body.facilityName;
        const location = req.body.location;
        const reportNumber = req.body.reportNumber;
        const visitDate = req.body.visitDate;
        
        // معالجة JSON
        let checklistData, observationsData;
        try { checklistData = typeof req.body.checklistData === 'string' ? JSON.parse(req.body.checklistData) : req.body.checklistData; } catch(e) { checklistData = {}; }
        try { observationsData = typeof req.body.observations === 'string' ? JSON.parse(req.body.observations) : req.body.observations; } catch(e) { observationsData = []; }

        // إنشاء التقرير
        const newReport = await Report.create({
            reportNumber,
            facilityName,
            location,
            visitDate,
            checklistData,
            inspectorId: req.userData.userId,
            status: 'pending_section_manager' // الحالة الافتراضية الجديدة
        });

        // إضافة الملاحظات
        if (observationsData && observationsData.length > 0) {
            const observationsToSave = observationsData.map((obs, index) => {
                const imageFieldName = `obs_image_${index}`;
                const uploadedFile = req.files ? req.files.find(f => f.fieldname === imageFieldName) : null;

                return {
                    reportId: newReport.id,
                    description: obs.description,
                    requiredAction: obs.requiredAction,
                    severity: obs.severity,
                    correctionDuration: obs.correctionDuration,
                    status: 'مفتوحة',
                    violationImage: uploadedFile ? `/uploads/${uploadedFile.filename}` : null
                };
            });
            await Observation.bulkCreate(observationsToSave);
        }

        res.status(201).json({ message: "تم حفظ التقرير بنجاح", reportId: newReport.id });
    } catch (error) {
        console.error("Error creating report:", error);
        res.status(500).json({ message: "حدث خطأ: " + error.message });
    }
};

// 2. جلب جميع التقارير
exports.getAllReports = async (req, res) => {
    try {
        const reports = await Report.findAll({
            include: [
                { model: User, as: 'inspector', attributes: ['fullName'] }
            ],
            order: [['createdAt', 'DESC']]
        });
        res.json(reports);
    } catch (error) {
        console.error("Error fetching reports:", error);
        res.status(500).json({ message: error.message });
    }
};

// 3. جلب تفاصيل تقرير
exports.getReportDetails = async (req, res) => {
    try {
        const report = await Report.findByPk(req.params.id, {
            include: [
                { model: User, as: 'inspector', attributes: ['fullName'] },
                { model: Observation, as: 'observations' }
            ]
        });
        if (!report) return res.status(404).json({ message: "التقرير غير موجود" });
        res.json(report);
    } catch (error) {
        res.status(500).json({ message: error.message });
    }
};