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

const router = express.Router();
router.get('/', authenticate, requirePermission('customers.view'), asyncHandler(async (req, res) => {
  const data = await customerService.listCustomers(req.user.shop_id, req.query);
  return success(res, data);
}));

router.post('/', authenticate, requirePermission('customers.create'), uploadCustomerFiles.fields([
  {name: 'photo', maxCount: 1},
  {name: 'idProofPhoto', maxCount: 1},
]), asyncHandler(async (req, res) => {
  const files = req.files || {};
  const data = await customerService.createCustomer(req.user.shop_id, req.user.id, {
    ...req.body,
    photoUrl: files.photo?.[0] ? `/uploads/customer-photos/${files.photo[0].filename}` : null,
    idProofUrl: files.idProofPhoto?.[0] ? `/uploads/id-proofs/${files.idProofPhoto[0].filename}` : null,
  });
  return success(res, data, 'Customer created');
}));

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

router.put('/:id', authenticate, requirePermission('customers.edit'), uploadCustomerFiles.fields([
  {name: 'photo', maxCount: 1},
  {name: 'idProofPhoto', maxCount: 1},
]), asyncHandler(async (req, res) => {
  const files = req.files || {};
  const data = await customerService.updateCustomer(req.user.shop_id, req.user.id, req.params.id, {
    ...req.body,
    photoUrl: files.photo?.[0] ? `/uploads/customer-photos/${files.photo[0].filename}` : null,
    idProofUrl: files.idProofPhoto?.[0] ? `/uploads/id-proofs/${files.idProofPhoto[0].filename}` : null,
  });
  return success(res, data, 'Customer updated');
}));

module.exports = router;
