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

const authMiddleware = require('../middleware/authMiddleware');
const adminOnly = require('../middleware/adminOnly');

// Controllers used by POST routes
const LoginController = require('../controller/login/LoginController');
const EmailVerificationController = require('../controller/auth/EmailVerificationController');
const PasswordResetController = require('../controller/password-reset/PasswordResetController');
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 PersonalRegisterController = require('../controller/register/PersonalRegisterController');
const CompanyRegisterController = require('../controller/register/CompanyRegisterController');
const GuestRegisterController = require('../controller/register/GuestRegisterController');
const PersonalDocumentController = require('../controller/documents/PersonalDocumentController');
const CompanyDocumentController = require('../controller/documents/CompanyDocumentController');
const ContractUploadController = require('../controller/documents/ContractUploadController');
const CoffeeController = require('../controller/admin/CoffeeController');
const PersonalProfileController = require('../controller/profile/PersonalProfileController');
const CompanyProfileController = require('../controller/profile/CompanyProfileController');
const AdminUserController = require('../controller/admin/AdminUserController');
const CompanyStampController = require('../controller/companyStamp/CompanyStampController'); // <-- added
const MatrixController = require('../controller/matrix/MatrixController'); // Matrix admin operations
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 DashboardPlatformsController = require('../controller/admin/DashboardPlatformsController');
const I18nPreferencesController = require('../controller/admin/I18nPreferencesController');
const MailTemplatesController = require('../controller/admin/MailTemplatesController');

const multer = require('multer');
const upload = multer({ storage: multer.memoryStorage() });

console.log('🛣️ Setting up POST routes');

// auth POSTs (BFF/frontend contract notes):
// - /login MUST set refreshToken cookie (Domain=.profit-planet.partners, Path=/, HttpOnly, Secure in prod, SameSite=Lax by default)
// - /refresh MUST rotate + also Set-Cookie refreshToken=<new> with SAME attributes
// - /logout MUST revoke server-side + clear cookie using SAME Domain+Path+SameSite+Secure (Max-Age=0)
router.post('/login', LoginController.login);
router.post('/refresh', LoginController.refresh);
router.post('/logout', LoginController.logout);
router.post('/send-verification-email', authMiddleware, EmailVerificationController.sendVerificationEmail);
router.post('/verify-email-code', authMiddleware, EmailVerificationController.verifyEmailCode);

// Password reset POSTs (moved)
router.post(
  '/request-password-reset',
  PasswordResetController.requestPasswordReset
);
router.post('/reset-password', PasswordResetController.resetPassword);

// Referral POSTs (moved from routes/referral.js)
router.post('/referral/create', authMiddleware, ReferralTokenController.create);
router.post('/referral/deactivate', authMiddleware, ReferralTokenController.deactivate);
router.post('/register/personal-referral', ReferralRegistrationController.registerPersonalReferral);
router.post('/register/company-referral', ReferralRegistrationController.registerCompanyReferral);

// Permissions POST (moved from routes/permissions.js)
router.post('/permissions', authMiddleware, PermissionController.create);

// Document templates upload & signature generation POSTs (moved)
router.post('/document-templates', authMiddleware, upload.single('file'), DocumentTemplateController.uploadTemplate);
router.post('/document-templates/:id/revise', authMiddleware, upload.single('file'), DocumentTemplateController.reviseTemplate);
router.post('/document-templates/:id/generate-pdf-with-signature', authMiddleware, DocumentTemplateController.generatePdfWithSignature);

// Document uploads (moved from routes/documents.js)
// NOTE: contract upload flow stores a temporary signature row and must delete it BEFORE UnitOfWork.commit().
router.post('/upload/personal-id', authMiddleware, upload.fields([{ name: 'front', maxCount: 1 }, { name: 'back', maxCount: 1 }]), PersonalDocumentController.uploadPersonalId);
router.post('/upload/company-id', authMiddleware, upload.fields([{ name: 'front', maxCount: 1 }, { name: 'back', maxCount: 1 }]), CompanyDocumentController.uploadCompanyId);
router.post('/upload/contract/personal', authMiddleware, upload.single('contract'), ContractUploadController.uploadPersonalContract);
router.post('/upload/contract/company', authMiddleware, upload.single('contract'), ContractUploadController.uploadCompanyContract);

// Profile completion POSTs (moved from routes/profile.js)
router.post('/profile/personal/complete', authMiddleware, PersonalProfileController.completeProfile);
router.post('/profile/company/complete', authMiddleware, CompanyProfileController.completeProfile);

// Admin POSTs (moved from routes/admin.js)
router.post('/admin/verify-user/:id', authMiddleware, adminOnly, AdminUserController.verifyUser);
router.post('/admin/mail-templates', authMiddleware, adminOnly, MailTemplatesController.create);
router.post('/admin/i18n/preferences', authMiddleware, adminOnly, I18nPreferencesController.post);
router.post('/i18n/preferences', authMiddleware, adminOnly, I18nPreferencesController.post);
router.post('/i18n/translations', authMiddleware, adminOnly, I18nPreferencesController.upsertTranslations);
router.post('/i18n/scan', authMiddleware, adminOnly, I18nPreferencesController.scan);
router.post('/admin/send-password-reset/:userId', authMiddleware, adminOnly, async (req, res) => {
  const userId = req.params.userId;
  // require here to avoid circular/top-level ordering issues
  const UnitOfWork = require('../database/UnitOfWork');
  const PersonalUserRepository = require('../repositories/user/personal/PersonalUserRepository');
  const CompanyUserRepository = require('../repositories/user/company/CompanyUserRepository');

  const uow = new UnitOfWork();
  let user = null;
  try {
    await uow.start();
    const personalRepo = new PersonalUserRepository(uow);
    const companyRepo = new CompanyUserRepository(uow);
    user = await personalRepo.findById(userId);
    if (!user) user = await companyRepo.findById(userId);
    if (!user) {
      await uow.rollback();
      return res.status(404).json({ success: false, message: 'User not found.' });
    }
    const email = user.email;
    await uow.commit();

    // forward to PasswordResetController using same interface as original route
    req.body = { email };
    return PasswordResetController.requestPasswordReset(req, res);
  } catch (err) {
    try { await uow.rollback(); } catch (_) {}
    console.error('[ADMIN SEND PASSWORD RESET] Error:', err);
    return res.status(500).json({ success: false, message: 'Internal server error.' });
  }
});

// NEW: ensure service sees a "company" user_type for admin users
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'; // mimic company to satisfy service checks
  }
  next();
}

// NEW: route-specific helper to ensure req.user has id/email from POST body
function ensureUserFromBody(req, res, next) {
  try {
    const bodyUserId = req.body?.userId ?? req.body?.id;
    const bodyEmail = req.body?.email;

    if (!req.user) req.user = {};
    if (!req.user.id && bodyUserId) req.user.id = bodyUserId;
    if (!req.user.email && bodyEmail) req.user.email = bodyEmail;

    // keep user_type/userType normalization intact
    if (!req.user.userType && req.user.user_type) req.user.userType = req.user.user_type;
    if (!req.user.user_type && req.user.userType) req.user.user_type = req.user.userType;

    next();
  } catch (e) {
    console.error('[ensureUserFromBody] Error:', e);
    next();
  }
}

// Company-stamp POST
router.post('/company-stamps', authMiddleware, adminOnly, forceCompanyForAdmin, CompanyStampController.upload);
// Admin: create coffee product (supports multipart files 'pictures' and legacy 'picture')
router.post('/admin/coffee', authMiddleware, adminOnly, upload.any(), CoffeeController.create);
// NEW: add user into matrix
router.post('/admin/matrix/add-user', authMiddleware, adminOnly, MatrixController.addUser); // already added
// NEW: remove matrix user and create vacancy
router.post('/admin/matrix/remove-user', authMiddleware, adminOnly, MatrixController.removeUser);
// NEW: assign user to vacancy
router.post('/admin/matrix/assign-vacancy', authMiddleware, adminOnly, MatrixController.assignVacancy);
// NEW: Admin create pool
router.post('/admin/pools', authMiddleware, adminOnly, PoolController.create);
// NEW: Admin add members to pool
router.post('/admin/pools/:id/members', authMiddleware, adminOnly, PoolController.addMembers);
// NEW: import VAT rates CSV
router.post('/tax/vat-rates/import', authMiddleware, adminOnly, upload.single('file'), TaxController.importVatRatesCsv);
// NEW: Admin create affiliate with logo upload
router.post('/admin/affiliates', authMiddleware, adminOnly, upload.single('logo'), AffiliateController.create);
// NEW: Admin create news with image upload
router.post('/admin/news', authMiddleware, adminOnly, upload.single('image'), NewsController.create);

// NEW: Admin dashboard platforms
router.post('/admin/dashboard-platforms', authMiddleware, adminOnly, DashboardPlatformsController.create);

// NEW: Dev Management SQL dump import (admin + super_admin)
router.post('/admin/dev/sql', authMiddleware, adminOnly, upload.single('file'), DevManagementController.importSqlDump);
// NEW: Dev Management Exoscale folder structure + loose file actions (admin + super_admin)
router.post('/admin/dev/exoscale/create-folder-structure', authMiddleware, adminOnly, DevManagementController.createFolderStructure);
router.post('/admin/dev/exoscale/move-loose-files', authMiddleware, adminOnly, DevManagementController.moveLooseFilesToContract);

// NEW: Admin move contract documents between /contract and /gdpr
router.post('/admin/contracts/:id/move', authMiddleware, adminOnly, DocumentTemplateController.moveUserContractDocument);

// Abonement POSTs
router.post('/abonements/subscribe', authMiddleware, AbonemmentController.subscribe);
router.post('/abonements/:id/pause', authMiddleware, AbonemmentController.pause);
router.post('/abonements/:id/resume', authMiddleware, AbonemmentController.resume);
router.post('/abonements/:id/cancel', authMiddleware, AbonemmentController.cancel);
router.post('/admin/abonements/:id/renew', authMiddleware, adminOnly, AbonemmentController.renew);
// CHANGED: ensure req.user has id/email from body for this route
router.post('/abonements/referred', authMiddleware, ensureUserFromBody, AbonemmentController.getReferredSubscriptions);

// NEW: Invoice POSTs
router.post('/invoices/:id/pay', authMiddleware, adminOnly, InvoiceController.pay);
router.post('/admin/invoices/email-report', authMiddleware, adminOnly, InvoiceController.sendEmailReport);
router.post('/admin/invoices', authMiddleware, adminOnly, upload.single('pdf'), InvoiceController.adminCreate);

// Existing registration handlers (keep)
router.post('/register/personal', (req, res) => {
  console.log('🔗 POST /register/personal route accessed');
  PersonalRegisterController.register(req, res);
});
router.post('/register/company', (req, res) => {
  console.log('🔗 POST /register/company route accessed');
  CompanyRegisterController.register(req, res);
});
router.post('/register/guest', (req, res) => {
  console.log('🔗 POST /register/guest route accessed');
  GuestRegisterController.register(req, res);
});

console.log('✅ POST routes configured successfully');

module.exports = router;