import express from 'express';
import { CrudController } from '../controllers/CrudController.js';
import { authenticateToken } from '../middlewares/authMiddleware.js';

const router = express.Router();

// The table mapper middleware is needed because we map dynamic entity endpoints to physical table names.
const entitiesMap = {
    'users': 'users', 'customers': 'customers', 'suppliers': 'suppliers',
    'materials': 'materials', 'paper-types': 'paper_types', 
    'finishing-options': 'finishing_options', 'printing-options': 'printing_options',
    'warehouses': 'warehouses', 'accounts': 'accounts', 
    'accounting-entries': 'accounting_entries', 'chatbots': 'chatbots',
    'partners': 'partners', 'production-steps': 'production_steps',
    'inventory/stock': 'inventory_stock', 'inventory/transactions': 'inventory_transactions',
    'customer-monitor-notes': 'customer_monitor_notes', 'delivery-notes': 'delivery_notes',
    'expenses': 'expenses', 'fixed-assets': 'fixed_assets', 
    'liabilities': 'liabilities', 'budgets': 'budgets', 
    'quotations': 'quotations', 'credit-notes': 'credit_notes',
    'quality-checks': 'quality_checks', 'plates': 'plates', 
    'finishing-blocks': 'finishing_blocks', 'commissions': 'commissions',
    'payslips': 'payslips', 'audit-logs': 'audit_logs', 
    'sst-history': 'sst_history', 'order-items': 'order_items',
    'attendance-records': 'attendance_records', 'employees': 'employees',
    'machines': 'machines', 'capital-contributions': 'capital_contributions',
    'roles': 'roles', 'purchase-orders': 'purchase_orders',
    'commission-persons': 'commission_persons', 'profiles': 'users',
    'biometric-credentials': 'biometric_credentials',
    'job-components': 'job_components',
    'job-finishing-operations': 'job_finishing_operations',
    'price-matrix': 'price_matrix',
    'parent-sheets': 'parent_sheets',
    'press-sheets': 'press_sheets'
};

const tableMapper = (req, res, next) => {
    // For nested routes like inventory/stock
    const pathSegments = req.path.split('/').filter(Boolean);
    const entity = (pathSegments.length > 1 && pathSegments[0] === 'inventory') ? `inventory/${pathSegments[1]}` : pathSegments[0];
    const table = entitiesMap[entity];
    
    if (!table) return res.status(404).json({ error: 'Entity not found in CRUD map' });
    req.params.table = table;
    
    // adjust req.params.id if it's there
    if (pathSegments.length > 1 && entity.startsWith('inventory')) {
        req.params.id = pathSegments[2];
    } else {
        req.params.id = pathSegments[1];
    }
    next();
};

router.get('/*', authenticateToken, tableMapper, CrudController.getMany);
router.post('/*', authenticateToken, tableMapper, CrudController.create);
router.put('/*', authenticateToken, tableMapper, CrudController.update);
router.delete('/*', authenticateToken, tableMapper, CrudController.remove);

export default router;
