const express = require('express');
const router = express.Router();
const multer = require('multer');
const authorize = require('../../../middlewares/authorize-sapps');
const importService = require('./import.service');
const path = require('path');
const fs = require('fs');

const storage = multer.diskStorage({
    destination: function (req, file, cb) {
        cb(null, './public/data/imports/');
    },
    filename: function (req, file, cb) {
        cb(null, req.body.filename ||  file.originalname);
    }
});

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

router.post('/upload-sales-data', authorize(), upload.single('file'), uploadSalesData);
router.post('/upload-sales-target', authorize(), upload.single('file'), uploadSalesTarget);
router.post('/import-sales', authorize(), importSalesData);
router.get('/get-sales-upload', authorize(), getAllSalesUpload);
router.delete("/delete-import-sales/:id", authorize(), deleteImportSalesData);

module.exports = router;


function uploadSalesData(req, res, next) {
    const filePath = path.join(__dirname, '../../../public/data/imports/', req.file.filename || req.file.originalname);
    
    // Cek apakah file sudah ada
    if (fs.existsSync(filePath)) {
        // Jika file sudah ada, Anda bisa memilih untuk tidak melakukan apa-apa
        // atau mengubah nama file baru jika diperlukan
        console.log('File already exists, keeping the old file.');
    }
    // Lanjutkan dengan proses upload
    const salesData = {
        ...req.body,
        filename: req.file ? req.file.filename : null
    };
    importService.uploadSalesData(salesData)
        .then(result => res.json(result))
        .catch(next);
}

function uploadSalesTarget(req, res, next) {
    const filePath = path.join(__dirname, '../../../public/data/imports/', req.file.filename || req.file.originalname);
    
    // Cek apakah file sudah ada
    if (fs.existsSync(filePath)) {
        // Jika file sudah ada, Anda bisa memilih untuk tidak melakukan apa-apa
        // atau mengubah nama file baru jika diperlukan
        console.log('File already exists, keeping the old file.');
    }
    // Lanjutkan dengan proses upload
    const salesData = {
        ...req.body,
        filename: req.file ? req.file.filename : null
    };
    importService.uploadSalesTarget(salesData)
        .then(result => res.json(result))
        .catch(next);
}

function importSalesData(req, res, next) {
    importService.importSalesData(req.body)
        .then(result => res.json(result))
        .catch(next);
}

function getAllSalesUpload(req, res, next) {
    importService
    .getAllSalesUpload()
    .then((result) => res.json(result))
    .catch(next);
}

function deleteImportSalesData(req, res, next) {
    importService
    .deleteImportSalesData(req.params.id)
    .then((result) => res.json(result))
    .catch(next);
}



function getFilename(req, res, next) {
    try {
        const filePath = path.join(__dirname, `../../../../public/data/imports/${req.params.id}`);

        if (!fs.existsSync(filePath)) {
            return res.status(404).json({ message: 'File not found' });
        }

        res.setHeader('Content-Disposition', `inline; filename="${req.params.id}"`);
        res.setHeader('Content-Type', 'application/pdf');

        res.sendFile(filePath, (err) => {
            if (err) {
                console.error('Error sending file: ', err);
                return res.status(500).json({ message: 'Internal server error' });
            }
        });
    } catch (error) {
        console.error('Error in getFilename:', error);
        res.status(500).json({ message: 'Internal server error' });
    }
}
