const { createCrudRoutes } = require('../database/crud');
const multer = require('multer');
const path = require('path');
const fs = require('fs');
const sharp = require('sharp');

let db;

function init(database) { db = database; }

function setupRoutes(app, auth) {
    const uploadDir = path.join(__dirname, '..', '..', 'data', 'partner_images');
    if (!fs.existsSync(uploadDir)) fs.mkdirSync(uploadDir, { recursive: true });

    const storage = multer.diskStorage({
        destination: uploadDir,
        filename: (req, file, cb) => {
            const ext = path.extname(file.originalname);
            cb(null, 'prt_' + Date.now() + ext);
        }
    });
    const upload = multer({
        storage,
        limits: { fileSize: 3 * 1024 * 1024 },
        fileFilter: (req, file, cb) => {
            const allowed = ['.jpg', '.jpeg', '.png', '.webp', '.svg'];
            cb(null, allowed.includes(path.extname(file.originalname).toLowerCase()));
        }
    });

    app.post('/api/admin/partners/upload', auth.authenticateToken, auth.requireAdmin, upload.single('image'), async (req, res) => {
        if (!req.file) return res.status(400).json({ error: 'Файл не загружен' });
        let fname = req.file.filename;
        const ext = path.extname(fname).toLowerCase();
        if (ext !== '.webp' && ext !== '.svg') {
            try {
                const webpName = path.basename(fname, ext) + '.webp';
                await sharp(req.file.path).webp({ quality: 85 }).toFile(path.join(uploadDir, webpName));
                fs.unlinkSync(req.file.path);
                fname = webpName;
            } catch (e) { console.error(e); }
        }
        res.json({ path: fname, url: `/data/partner_images/${fname}` });
    });

    createCrudRoutes(app, auth, 'partners', {
        fields: ['name', 'logo_path', 'sort_order', 'is_active']
    });
}

module.exports = { init, setupRoutes };
