import type { NextApiRequest, NextApiResponse } from 'next';
import { createRouter, expressWrapper } from "next-connect";
import multer from 'multer';
import excel from "../../src/helpers/excel";
import common from "../../src/helpers/common";

const upload = multer({
  storage: multer.memoryStorage(),
});
const progressStore = {};

// Update the progressStore instead of the session
function updateProgress(fileId, progress) {
  progressStore[fileId] = progress;
};

function getProgress(fileId) {
  return progressStore[fileId] || 0;
};


const router = createRouter<NextApiRequest, NextApiResponse>();

router.use(expressWrapper(upload.single('file')))
  .post(async (req, res) => {
    try {
      if (!req.file) {
        return res.status(400).json({ message: 'No file uploaded' });
      }

      // Extract the action and date from query parameters
      const { action, date } = req.query;
      // Generate a unique upload ID
      const fileId = new Date().getTime().toString();
      // Initialize progress
      updateProgress(fileId, 1);

      if (action === 'readword') {
        // Start file processing asynchronously
        processWordFile(req.file.buffer, date, fileId, true)
          .catch(error => {
            // Handle any errors here
            updateProgress(fileId, 0);
            console.error('Грешка при обработката на файла:', error);
          });

        // Respond immediately
        res.status(200).json({ message: 'Файла е качен. Започна обработката на данните.', fileId });

      } else {
        // Handle other actions or return an error
        res.status(400).json({ message: 'Невалидно или неоточнено действие.' });
      }
    } catch (error) {
      // Error handling
      res.status(500).json({ message: 'Вътрешна грешка на сървъра', error: error.message });
    }
  })
  .get((req, res) => {
    console.log('Progress check handler');
    const { fileId } = req.query;
    var progress = getProgress(fileId);
    res.status(200).json({ progress });
  }
  )


// Asynchronous file processing function
async function processWordFile(fileBuffer, dateString, fileId, createAvailabilities) {
  const [year, month, day] = dateString.split('-');
  await excel.ReadDocxFileForMonth(null, fileBuffer, month, year, (currentProgress) => {
    updateProgress(fileId, currentProgress);
  }, createAvailabilities);
}

// // Progress check handler - moved to server.js
// router.get('/progress/:id', (req, res) => {
//   const { fileId } = req.query;
//   var progress = getProgress(fileId);
//   res.status(200).json({ progress });
// });

const handler = (req: NextApiRequest, res: NextApiResponse) => {
  router.run(req, res);
};

export default handler;

export const config = {
  api: {
    bodyParser: false, // Necessary for file upload
  },
};
