const express = require('express');
const {authenticate, requirePermission} = require('../middleware/auth');
const reportService = require('../services/reportService');
const {asyncHandler} = require('../utils/asyncHandler');
const {success} = require('../utils/apiResponse');

const router = express.Router();

router.get('/', authenticate, requirePermission('reports.view'), asyncHandler(async (req, res) => {
  const data = await reportService.listReports();
  return success(res, data);
}));

router.post('/availability', authenticate, requirePermission('reports.export'), asyncHandler(async (req, res) => {
  const data = await reportService.checkReportAvailability(req.user.shop_id, req.body);
  return success(res, data);
}));

router.post('/export/pdf', authenticate, requirePermission('reports.export'), asyncHandler(async (req, res) => {
  const file = await reportService.exportReport(req.user.shop_id, req.user.id, 'PDF', req.body);
  res.setHeader('Content-Type', file.contentType);
  res.setHeader('Content-Disposition', `attachment; filename="${file.filename}"`);
  return res.send(file.buffer);
}));

router.post('/export/excel', authenticate, requirePermission('reports.export'), asyncHandler(async (req, res) => {
  const file = await reportService.exportReport(req.user.shop_id, req.user.id, 'Excel', req.body);
  res.setHeader('Content-Type', file.contentType);
  res.setHeader('Content-Disposition', `attachment; filename="${file.filename}"`);
  return res.send(file.buffer);
}));

module.exports = router;
