const express = require('express');
const multer = require('multer');
const {authenticate, requirePermission} = require('../middleware/auth');
const loanService = require('../services/loanService');
const {asyncHandler} = require('../utils/asyncHandler');
const {success} = require('../utils/apiResponse');
const {createStorage, jewelryDirectory} = require('../config/uploads');

const router = express.Router();
const upload = multer({
  storage: createStorage(jewelryDirectory),
  limits: {fileSize: 8 * 1024 * 1024, files: 50},
  fileFilter: (_request, file, callback) => {
    if (file.mimetype && file.mimetype.startsWith('image/')) { callback(null, true); return; }
    callback(new Error('Only image files are allowed.'));
  },
});

router.get('/', authenticate, requirePermission('loans.view'), asyncHandler(async (req, res) => {
  const data = await loanService.listLoans(req.user.shop_id, req.query);
  return success(res, data);
}));

router.post('/', authenticate, requirePermission('loans.create'), upload.any(), asyncHandler(async (req, res) => {
  const payload = {...req.body};
  if (typeof payload.jewelryItems === 'string') {
    payload.jewelryItems = JSON.parse(payload.jewelryItems);
  }
  const photosByItem = {};
  (req.files || []).forEach(file => {
    const match = /^jewelryImages_(\d+)$/.exec(file.fieldname);
    if (!match) { return; }
    const itemIndex = match[1];
    photosByItem[itemIndex] = photosByItem[itemIndex] || [];
    photosByItem[itemIndex].push(`/uploads/jewels/${file.filename}`);
  });
  payload.jewelryItems = (payload.jewelryItems || []).map((item, index) => ({
    ...item,
    photoUrl: photosByItem[index]?.join(';') || item.photoUrl || null,
  }));
  const data = await loanService.createLoan(req.user.shop_id, req.user.id, payload);
  return success(res, data, 'Loan created');
}));

router.get('/:id', authenticate, requirePermission('loans.view'), asyncHandler(async (req, res) => {
  const data = await loanService.getLoan(req.user.shop_id, req.params.id);
  return success(res, data);
}));

router.post('/:id/payments', authenticate, requirePermission('loans.manage'), asyncHandler(async (req, res) => {
  const data = await loanService.receivePayment(req.user.shop_id, req.user.id, req.params.id, req.body);
  return success(res, data, 'Payment received');
}));

router.post('/:id/renew', authenticate, requirePermission('loans.manage'), asyncHandler(async (req, res) => {
  const data = await loanService.renewLoan(req.user.shop_id, req.user.id, req.params.id, req.body);
  return success(res, data, 'Loan renewed');
}));

router.post('/:id/close', authenticate, requirePermission('loans.manage'), asyncHandler(async (req, res) => {
  const data = await loanService.closeLoan(req.user.shop_id, req.user.id, req.params.id, req.body);
  return success(res, data, 'Loan closed');
}));

router.get('/:id/pdf', authenticate, requirePermission('loans.view'), asyncHandler(async (req, res) => {
  const file = await loanService.generateLoanPdf(req.user.shop_id, req.params.id);
  res.setHeader('Content-Type', 'application/pdf');
  res.setHeader('Content-Disposition', `attachment; filename="${file.filename}"`);
  return res.send(file.buffer);
}));

module.exports = router;
