const express = require('express');
const path = require('path');
const router = express.Router();

// NOTE: If the frontend ever calls backend routes directly with cookies,
// CORS must allow credentials and a non-* origin; otherwise refreshToken cookies won't be sent.

const authMiddleware = require('../middleware/authMiddleware');
const adminOnly = require('../middleware/adminOnly');
const UserSettingsController = require('../controller/auth/UserSettingsController');
const ReferralTokenController = require('../controller/referral/ReferralTokenController');
const ReferralRegistrationController = require('../controller/referral/ReferralRegistrationController');
const PermissionController = require('../controller/permissions/PermissionController');
const DocumentTemplateController = require('../controller/documentTemplate/DocumentTemplateController');
const AdminUserController = require('../controller/admin/AdminUserController');
const UserDocumentController = require('../controller/documents/UserDocumentController');
const ServerStatusController = require('../controller/admin/ServerStatusController');
const UserController = require('../controller/auth/UserController');
const UserStatusController = require('../controller/auth/UserStatusController');
const CompanyStampController = require('../controller/companyStamp/CompanyStampController'); // <-- added
const MatrixController = require('../controller/matrix/MatrixController'); // <-- added
const CoffeeController = require('../controller/admin/CoffeeController');
const PoolController = require('../controller/pool/PoolController');
const TaxController = require('../controller/tax/taxController');
const AffiliateController = require('../controller/affiliate/AffiliateController');
const AbonemmentController = require('../controller/abonemments/AbonemmentController');
const NewsController = require('../controller/news/NewsController');
const InvoiceController = require('../controller/invoice/InvoiceController'); // NEW
const DevManagementController = require('../controller/dev/DevManagementController');
const CompanySettingsController = require('../controller/admin/CompanySettingsController');
const DashboardPlatformsController = require('../controller/admin/DashboardPlatformsController');
const ShippingFeesController = require('../controller/admin/ShippingFeesController');
const LoginController = require('../controller/login/LoginController');
const I18nPreferencesController = require('../controller/admin/I18nPreferencesController');
const MailTemplatesController = require('../controller/admin/MailTemplatesController');

const AUTH_VALIDATE_ROUTE_PATH = '/auth/validate';

// small helpers copied from original files

// NEW helper used by company-stamp routes
function forceCompanyForAdmin(req, res, next) {
  if (req.user && ['admin','super_admin'].includes(req.user.role) && req.user.user_type !== 'company') {
    req.user.user_type = 'company';
  }
  next();
}

// === GET routes moved from other files ===

// auth.js GETs
router.get(AUTH_VALIDATE_ROUTE_PATH, LoginController.validate);
router.get('/me', authMiddleware, UserController.getMe);
router.get('/user/status', authMiddleware, UserStatusController.getStatus);
router.get('/user/status-progress', authMiddleware, UserStatusController.getStatusProgress);
router.get('/users/:id/full', authMiddleware, UserController.getFullUserData);
router.get('/user/settings', authMiddleware, UserSettingsController.getSettings);
router.get('/users/:id/permissions', authMiddleware, PermissionController.getUserPermissions);
router.get('/admin/users/:id/full', authMiddleware, adminOnly, AdminUserController.getFullUserAccountDetails);
router.get('/admin/users/:id/detailed', authMiddleware, adminOnly, AdminUserController.getDetailedUserInfo);
router.get('/admin/company-settings', authMiddleware, adminOnly, CompanySettingsController.get);
router.get('/admin/i18n/preferences', authMiddleware, adminOnly, I18nPreferencesController.get);
router.get('/i18n/preferences', authMiddleware, adminOnly, I18nPreferencesController.get);
router.get('/i18n/translations', authMiddleware, adminOnly, I18nPreferencesController.getTranslations);
router.get('/i18n/scan', authMiddleware, adminOnly, I18nPreferencesController.scan);
router.get('/users/:id/documents', authMiddleware, UserController.getUserDocumentsAndContracts);
router.get('/verify-password-reset', (req, res) => { /* Note: was moved from PasswordResetController.verifyPasswordResetToken */ res.status(204).end(); }); // keep placeholder if controller already registered via other verb

// admin.js GETs
router.get('/admin/user-stats', authMiddleware, adminOnly, AdminUserController.getUserStats);
router.get('/admin/user-list', authMiddleware, adminOnly, AdminUserController.getUserList);
router.get('/admin/mail-templates', authMiddleware, adminOnly, MailTemplatesController.list);
router.get('/admin/mail-templates/:id', authMiddleware, adminOnly, MailTemplatesController.getById);
router.get('/admin/verification-pending-users', authMiddleware, adminOnly, AdminUserController.getVerificationPendingUsers);
router.get('/admin/unverified-users', authMiddleware, adminOnly, AdminUserController.getUnverifiedUsers);
router.get('/admin/user/:id/documents', authMiddleware, adminOnly, UserDocumentController.getAllDocumentsForUser);
router.get('/admin/server-status', authMiddleware, adminOnly, ServerStatusController.getStatus);
router.get('/admin/dev/exoscale/folder-structure-issues', authMiddleware, adminOnly, DevManagementController.listFolderStructureIssues);
router.get('/admin/dev/exoscale/loose-files', authMiddleware, adminOnly, DevManagementController.listLooseFiles);
router.get('/admin/dev/exoscale/ghost-directories', authMiddleware, adminOnly, DevManagementController.listGhostDirectories);
router.get('/admin/dev/exoscale/download-archive', authMiddleware, adminOnly, DevManagementController.downloadStorageArchive);
// Admin: dashboard platforms
router.get('/admin/dashboard-platforms', authMiddleware, adminOnly, DashboardPlatformsController.list);

// Public: dashboard platforms (active only)
router.get('/dashboard-platforms', DashboardPlatformsController.listPublic);

// Public: shipping fees (60/120)
router.get('/shipping-fees', ShippingFeesController.listPublic);
// Contract preview for admin: latest active by user type
router.get('/admin/contracts/:id/preview', authMiddleware, adminOnly, DocumentTemplateController.previewLatestForUser);
// Admin: list all contract documents for a user
router.get('/admin/contracts/:id/documents', authMiddleware, adminOnly, DocumentTemplateController.listUserContractDocuments);
// Admin: list contract files from object storage for a user
router.get('/admin/contracts/:id/files', authMiddleware, adminOnly, DocumentTemplateController.listUserContractFiles);

// permissions.js GETs
router.get('/permissions', authMiddleware, PermissionController.list);

// referral.js GETs
router.get('/referral/list', authMiddleware, ReferralTokenController.list);
router.get('/referral/stats', authMiddleware, ReferralTokenController.stats);
router.get('/referral/info/:token', ReferralRegistrationController.getReferrerInfo);
router.get('/referral/referred-users', authMiddleware, ReferralTokenController.referredUsers);

// userSettings.js GETs
router.get('/settings', authMiddleware, UserSettingsController.getSettings);

// contracts.js (file downloads)
router.get('/contracts/personal', authMiddleware, (req, res) => {
  const filePath = path.join(__dirname, '../contractTemplates/personal/test.pdf');
  res.download(filePath, 'personal-service-contract.pdf', (err) => {
    if (err) res.status(404).json({ success: false, message: 'Personal contract not found' });
  });
});
router.get('/contracts/company', authMiddleware, (req, res) => {
  const filePath = path.join(__dirname, '../contractTemplates/company/test.pdf');
  res.download(filePath, 'company-service-contract.pdf', (err) => {
    if (err) res.status(404).json({ success: false, message: 'Company contract not found' });
  });
});

// User: preview latest active contract (HTML) for authenticated user
router.get('/contracts/preview/latest', authMiddleware, DocumentTemplateController.previewLatestForMe);

// User: preview latest active ABO contract (HTML) for authenticated user
router.get('/contracts/abo/active', authMiddleware, DocumentTemplateController.previewLatestAboForMe);

// documentTemplates.js GETs
router.get('/document-templates', authMiddleware, DocumentTemplateController.listTemplates);
router.get('/document-templates/:id', authMiddleware, DocumentTemplateController.getTemplate);
router.get('/document-templates-public', authMiddleware, adminOnly, DocumentTemplateController.listTemplatesPublic);
router.get('/document-templates/:id/generate-pdf', authMiddleware, DocumentTemplateController.generatePdf);
router.get('/document-templates/:id/preview', authMiddleware, DocumentTemplateController.previewTemplate);
router.get('/document-templates/:id/preview-pdf', authMiddleware, DocumentTemplateController.previewPdf);
router.get('/document-templates/active/mine', authMiddleware, DocumentTemplateController.listMyActiveTemplates);
router.get('/document-templates/:id/download-pdf', authMiddleware, DocumentTemplateController.downloadPdf);
router.get('/api/document-templates', authMiddleware, adminOnly, DocumentTemplateController.listTemplatesFiltered);

// Company-stamp GETs
router.get('/company-stamps/mine', authMiddleware, adminOnly, forceCompanyForAdmin, CompanyStampController.listMine);
router.get('/company-stamps/mine/active', authMiddleware, adminOnly, forceCompanyForAdmin, CompanyStampController.activeMine);
router.get('/company-stamps/all', authMiddleware, adminOnly, forceCompanyForAdmin, CompanyStampController.listAll);
// Admin: coffee products
router.get('/admin/coffee', authMiddleware, adminOnly, CoffeeController.list);
router.get('/admin/coffee/active', authMiddleware, adminOnly, CoffeeController.listActive);
router.get('/admin/coffee/:id/pictures', authMiddleware, adminOnly, CoffeeController.getPictures);
router.get('/coffee/active', authMiddleware, CoffeeController.listActive);
router.get('/coffee/:id/pictures', authMiddleware, CoffeeController.getPictures);


// Matrix GETs
router.get('/matrix/create', authMiddleware, adminOnly, MatrixController.create);
router.get('/matrix/stats', authMiddleware, adminOnly, MatrixController.stats);
router.get('/admin/matrix/users', authMiddleware, adminOnly, MatrixController.getMatrixUserforAdmin);
router.get('/admin/matrix/user-candidates', authMiddleware, adminOnly, MatrixController.searchCandidates);

// NEW: Matrix overview for authenticated user
router.get('/matrix/me/overview', authMiddleware, MatrixController.getMyOverview);

// NEW: Matrix POST (admin)
router.post('/admin/matrix/add-user', authMiddleware, adminOnly, MatrixController.addUser);

// NEW: Admin list pools
router.get('/admin/pools', authMiddleware, adminOnly, PoolController.list);
// NEW: Admin list pool members
router.get('/admin/pools/:id/members', authMiddleware, adminOnly, PoolController.listMembers);
// NEW: Admin diagnose pool inflow for invoice
router.get('/admin/pools/inflow-diagnostics', authMiddleware, adminOnly, PoolController.inflowDiagnostics);
// NEW: Admin pool inflow stats
router.get('/admin/pools/:id/stats', authMiddleware, adminOnly, PoolController.poolStats);

// NEW: User matrices list and per-instance overview
router.get('/matrix/me/list', authMiddleware, MatrixController.listMyMatrices);
router.get('/matrix/:id/overview', authMiddleware, MatrixController.getMyOverviewByInstance);
// NEW: User matrix summary (totals and fill)
router.get('/matrix/:id/summary', authMiddleware, MatrixController.getMyMatrixSummary);

// Tax GETs
router.get('/tax/vat-rates', authMiddleware, TaxController.getAllVatRates);
router.get('/tax/vat-history/:countryCode', authMiddleware, adminOnly, TaxController.getVatHistory);

// NEW: Admin list vacancies for a matrix
router.get('/admin/matrix/vacancies', authMiddleware, adminOnly, MatrixController.listVacancies);

// Affiliate Management Routes (Admin)
router.get('/admin/affiliates', authMiddleware, adminOnly, AffiliateController.list);

// Public Affiliates Route (Active only)
router.get('/affiliates/active', AffiliateController.listActive);

// Abonement GETs
router.get('/abonements/mine', authMiddleware, AbonemmentController.getMine);
router.get('/abonements/mine/status', authMiddleware, AbonemmentController.getMineStatus);
router.get('/abonements/:id/invoices', authMiddleware, AbonemmentController.getInvoices);
router.get('/abonements/:id/history', authMiddleware, AbonemmentController.getHistory);
router.get('/admin/abonements', authMiddleware, adminOnly, AbonemmentController.adminList);

// News Manager Routes
router.get('/admin/news', authMiddleware, adminOnly, NewsController.list);
router.get('/news/active', NewsController.listActive);
router.get('/news/:slug', NewsController.getPublic);

// NEW: Invoice GETs
router.get('/invoices/mine', authMiddleware, InvoiceController.listMine);
router.get('/invoices/:id/pdf', authMiddleware, InvoiceController.downloadPdf);
router.get('/admin/invoices', authMiddleware, adminOnly, InvoiceController.adminList);
router.get('/admin/invoices/revenue-summary', authMiddleware, adminOnly, InvoiceController.revenueSummary);
router.get('/admin/invoices/:id/detail', authMiddleware, adminOnly, InvoiceController.getDetail);

// NOTE: Contract signing uses UnitOfWork; any DB cleanup must happen before commit() closes the connection.

// export
module.exports = router;