const express = require('express');
const { catchErrors } = require('@/handlers/errorHandlers');
const { singleStorageUpload } = require('@/middlewares/uploadMiddleware');
const router = express.Router();

const appControllers = require('@/controllers/appControllers');
const { routesList } = require('@/models/utils');
const workflowController = require('@/controllers/platformControllers/workflowController');
const dealController = require('@/controllers/platformControllers/dealController');
const aiController = require('@/controllers/platformControllers/aiController');
const landingFormController = require('@/controllers/platformControllers/landingFormController');
const socialPostController = require('@/controllers/platformControllers/socialPostController');
const automationController = require('@/controllers/platformControllers/automationController');
const accessControlController = require('@/controllers/platformControllers/accessControlController');
const enterpriseWorkflowController = require('@/controllers/platformControllers/enterpriseWorkflowController');
const reportController = require('@/controllers/platformControllers/reportController');
const growthWorkspaceController = require('@/controllers/platformControllers/growthWorkspaceController');
const agentController = require('@/controllers/platformControllers/agentController');
const knowledgeController = require('@/controllers/platformControllers/knowledgeController');
const socialWorkspaceController = require('@/controllers/platformControllers/socialWorkspaceController');
const notificationController = require('@/controllers/platformControllers/notificationController');
const posController = require('@/controllers/platformControllers/posController');
const userManagementController = require('@/controllers/platformControllers/userManagementController');
const formBuilderController = require('@/controllers/platformControllers/formBuilderController');

const routerApp = (entity, controller) => {
  router.route(`/${entity}/create`).post(catchErrors(controller['create']));
  router.route(`/${entity}/read/:id`).get(catchErrors(controller['read']));
  router.route(`/${entity}/update/:id`).patch(catchErrors(controller['update']));
  router.route(`/${entity}/delete/:id`).delete(catchErrors(controller['delete']));
  router.route(`/${entity}/search`).get(catchErrors(controller['search']));
  router.route(`/${entity}/list`).get(catchErrors(controller['list']));
  router.route(`/${entity}/listAll`).get(catchErrors(controller['listAll']));
  router.route(`/${entity}/filter`).get(catchErrors(controller['filter']));
  router.route(`/${entity}/summary`).get(catchErrors(controller['summary']));
  router.route(`/${entity}/export`).get(catchErrors(controller['export']));

  if (entity === 'invoice' || entity === 'quote' || entity === 'payment') {
    router.route(`/${entity}/mail`).post(catchErrors(controller['mail']));
  }

  if (entity === 'quote') {
    router.route(`/${entity}/convert/:id`).get(catchErrors(controller['convert']));
  }
};

routesList.forEach(({ entity, controllerName }) => {
  const controller = appControllers[controllerName];
  routerApp(entity, controller);
});

router.route('/deal/:id/stage').patch(catchErrors(dealController.updateStage));
router.route('/workflows/deal-won').post(catchErrors(workflowController.dealWon));
router.route('/offer/convert/:id').post(catchErrors(enterpriseWorkflowController.convertOffer));
router.route('/invoice/:id/record-payment').post(catchErrors(enterpriseWorkflowController.recordPayment));
router.route('/payment/:id/reconcile').patch(catchErrors(enterpriseWorkflowController.reconcilePayment));
router.route('/order/:id/status').patch(catchErrors(enterpriseWorkflowController.updateOrderStatus));
router.route('/purchaseorder/:id/status').patch(catchErrors(enterpriseWorkflowController.updatePurchaseOrderStatus));
router.route('/landingform/capture').post(catchErrors(landingFormController.capture));
router.route('/publicform/submit/:slug').post(catchErrors(landingFormController.submit));
router.route('/socialpost/schedule').post(catchErrors(socialPostController.schedule));
router.route('/ai/content/generate').post(catchErrors(aiController.generateContent));
router.route('/ai/brand-asset/generate').post(catchErrors(aiController.generateBrandAsset));
router.route('/ai/campaign/draft').post(catchErrors(aiController.draftCampaign));
router.route('/ai/document/generate-from-template').post(catchErrors(aiController.generateFromTemplate));
router.route('/ai/document/templates').get(catchErrors(appControllers.documentTemplateController.list));
router.route('/ai/workspace/assets').get(catchErrors(growthWorkspaceController.aiAssets));
router.route('/agent/templates').get(catchErrors(agentController.templates));
router.route('/agent/tools').get(catchErrors(agentController.tools));
router.route('/agent/from-template').post(catchErrors(agentController.createFromTemplate));
router.route('/agent/:id/version').get(catchErrors(agentController.version));
router.route('/agent/:id/publish').post(catchErrors(agentController.publish));
router.route('/agent/:id/test').post(catchErrors(agentController.test));
router.route('/agent/:id/run').post(catchErrors(agentController.run));
router.route('/agent/calendar').get(catchErrors(agentController.calendar));
router.route('/agent/schedule').get(catchErrors(agentController.schedule));
router.route('/agent/:id/schedule/preview').post(catchErrors(agentController.schedulePreview));
router.route('/agent/run/history').get(catchErrors(agentController.runs));
router.route('/agent/run/:id').get(catchErrors(agentController.runDetail));
router.route('/agent/run/:id/retry').post(catchErrors(agentController.retry));
router.route('/agent/run/:id/cancel').post(catchErrors(agentController.cancel));
router.route('/agent/approval').get(catchErrors(agentController.approvals));
router.route('/agent/approval/:id/decide').post(catchErrors(agentController.decideApproval));
router.route('/agent/assistant/chat').post(catchErrors(agentController.assistant));
router.route('/agent/run-due').post(catchErrors(agentController.runDue));
router.route('/integrationaccount/providers').get(catchErrors(appControllers.integrationaccountController.providers));
router.route('/integrationaccount/test/:provider').post(catchErrors(appControllers.integrationaccountController.testConnection));
router.route('/integrationaccount/secret/:provider').delete(catchErrors(appControllers.integrationaccountController.clearSecret)).post(catchErrors(appControllers.integrationaccountController.clearSecret));
router.route('/knowledge/source/:id/ingest').post(catchErrors(knowledgeController.ingest));
router.route('/knowledge/search').get(catchErrors(knowledgeController.search));
router.route('/social/calendar').get(catchErrors(socialWorkspaceController.calendar));
router.route('/social/post/preview').post(catchErrors(socialWorkspaceController.preview));
router.route('/social/post/schedule').post(catchErrors(socialWorkspaceController.schedule));
router.route('/social/post/:id/approve').post(catchErrors(socialWorkspaceController.approve));
router.route('/social/post/:id/reschedule').patch(catchErrors(socialWorkspaceController.reschedule));
router.route('/social/post/:id/publish').post(catchErrors(socialWorkspaceController.publish));
router.route('/social/post/:id/retry').post(catchErrors(socialWorkspaceController.retry));
router.route('/social/metrics').get(catchErrors(socialWorkspaceController.metrics));
router.route('/marketing/workspace/summary').get(catchErrors(growthWorkspaceController.marketingSummary));
router.route('/campaign/launch').post(catchErrors(growthWorkspaceController.launchCampaign));
router.route('/automation/run-due').post(catchErrors(automationController.runDue));
router.route('/automation/run-history').get(catchErrors(automationController.runHistory));
router.route('/automation/calendar').get(catchErrors(automationController.calendar));
router.route('/automation/run/:id/retry').post(catchErrors(automationController.retryRun));
router.route('/automation/preview').post(catchErrors(growthWorkspaceController.automationPreview));
router.route('/automation/workspace/summary').get(catchErrors(growthWorkspaceController.automationSummary));
router.route('/automation/operations/summary').get(catchErrors(automationController.operationsSummary));
router.route('/notification').get(catchErrors(notificationController.list));
router.route('/notification/:id/read').patch(catchErrors(notificationController.read));
router.route('/notification/read-all').post(catchErrors(notificationController.readAll));
router.route('/notification/preferences').get(catchErrors(notificationController.preferences)).patch(catchErrors(notificationController.updatePreferences));
router.route('/notification/unread-count').get(catchErrors(notificationController.unread));
router.route('/reports/overview').get(catchErrors(reportController.overview));
router.route('/pos/summary').get(catchErrors(posController.summary));
router.route('/pos/session/open').post(catchErrors(posController.openSession));
router.route('/pos/session/current').get(catchErrors(posController.currentSession));
router.route('/pos/session/:id/close').post(catchErrors(posController.closeSession));
router.route('/pos/checkout').post(catchErrors(posController.checkout));
router.route('/pos/sale/history').get(catchErrors(posController.saleHistory));
router.route('/pos/sale/export').get(catchErrors(posController.exportSales));
router.route('/pos/report').get(catchErrors(posController.report));
router.route('/pos/receipt/:id/reprint').post(catchErrors(posController.reprintReceipt));
router.route('/pos/barcode/:productId').get(catchErrors(posController.barcode));
router.route('/admin-access/users').get(catchErrors(userManagementController.list)).post(catchErrors(userManagementController.create));
router.route('/admin-access/users/:id').patch(catchErrors(userManagementController.update));
router.route('/admin-access/users/:id/reset-password').post(catchErrors(userManagementController.resetPassword));
router.route('/admin-access/users/:id/sessions').get(catchErrors(userManagementController.sessions)).delete(catchErrors(userManagementController.revokeAllSessions));
router.route('/admin-access/users/:id/sessions/:sessionId').delete(catchErrors(userManagementController.revokeSession));
router.route('/form-builder/definitions').get(catchErrors(formBuilderController.definitions));
router.route('/form-builder/definition').post(catchErrors(formBuilderController.saveDefinition));
router.route('/form-builder/definition/:id').patch(catchErrors(formBuilderController.updateDefinition));
router.route('/form-builder/submit/:id').post(catchErrors(formBuilderController.submit));
router.route('/form-builder/submissions').get(catchErrors(formBuilderController.submissions));
router.route('/permission/catalog').get(catchErrors(accessControlController.listPermissionCatalog));
router.route('/role/bootstrap-defaults').post(catchErrors(accessControlController.bootstrapDefaults));
router.route('/role/admin-access').get(catchErrors(accessControlController.listAdminAccess));
router.route('/role/admin-access/:id').patch(catchErrors(accessControlController.updateAdminAccess));

// Finance Document Vault — upload, list, delete
router
  .route('/finance/document/upload')
  .post(
    singleStorageUpload({ entity: 'financedocument', fieldName: 'fileUrl', fileType: 'default' }),
    catchErrors(appControllers.documentController.create),
  );
router.route('/finance/document/list').get(catchErrors(appControllers.documentController.list));
router.route('/finance/document/:id').delete(catchErrors(appControllers.documentController.delete));

module.exports = router;
