const express = require('express');
const { StoreSetting } = require('../models');
const { authenticateToken, isAdmin } = require('../middleware/auth');
const multer = require('multer');
const path = require('path');
const fs = require('fs');
const router = express.Router();

// Configure Multer
const storage = multer.diskStorage({
    destination: function (req, file, cb) {
        const uploadPath = path.join(__dirname, '../uploads/settings');
        // Create directory if it doesn't exist
        if (!fs.existsSync(uploadPath)) {
            fs.mkdirSync(uploadPath, { recursive: true });
        }
        cb(null, uploadPath);
    },
    filename: function (req, file, cb) {
        const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9);
        cb(null, 'logo-' + uniqueSuffix + path.extname(file.originalname));
    }
});

const upload = multer({ storage: storage });

// Get Settings (singleton)
router.get('/', async (req, res) => {
    try {
        let settings = await StoreSetting.findOne();
        if (!settings) {
            settings = await StoreSetting.create({});
        }
        res.json(settings);
    } catch (error) {
        res.status(500).json({ message: 'Server error', error: error.message });
    }
});

// Update Settings
router.put('/', authenticateToken, isAdmin, upload.fields([{ name: 'logo', maxCount: 1 }, { name: 'favicon', maxCount: 1 }]), async (req, res) => {
    try {
        console.log("PUT /settings hit");
        console.log("Files:", req.files);
        console.log("Body:", req.body);

        const {
            storeName, email, phone, address,
            qrisEnabled, qrisImage,
            baseRate, enableFreeShipping, freeShippingThreshold
        } = req.body;

        let settings = await StoreSetting.findOne();
        if (!settings) {
            settings = await StoreSetting.create({});
        }

        const updateData = {
            storeName, email, phone, address,
            qrisEnabled: qrisEnabled === 'true' || qrisEnabled === true, // Handle FormData string conversion
            qrisImage,
            baseRate,
            enableFreeShipping: enableFreeShipping === 'true' || enableFreeShipping === true,
            freeShippingThreshold
        };

        // Handle Logo Upload
        if (req.files && req.files['logo']) {
            updateData.logo = `/uploads/settings/${req.files['logo'][0].filename}`;
        } else if (req.body.logo !== undefined) {
            updateData.logo = req.body.logo;
        }

        // Handle Favicon Upload
        if (req.files && req.files['favicon']) {
            updateData.favicon = `/uploads/settings/${req.files['favicon'][0].filename}`;
        } else if (req.body.favicon !== undefined) {
            updateData.favicon = req.body.favicon;
        }

        await settings.update(updateData);

        res.json(settings);
    } catch (error) {
        console.error("Settings update error:", error);
        res.status(500).json({ message: 'Server error', error: error.message });
    }
});

module.exports = router;
