// Organization Routes - B2B Enterprise
const express = require('express');
const router = express.Router();
const { protect } = require('../middleware/authMiddleware');
const multer = require('multer');
const path = require('path');

// Configure multer for logo uploads
const storage = multer.diskStorage({
    destination: (req, file, cb) => cb(null, 'public/uploads/org-logos'),
    filename: (req, file, cb) => cb(null, `org-${req.params.id}-${Date.now()}${path.extname(file.originalname)}`)
});
const upload = multer({ storage, limits: { fileSize: 2 * 1024 * 1024 } }); // 2MB limit

const {
    createOrganization,
    getOrganization,
    getMembers,
    inviteMember,
    acceptInvite,
    removeMember,
    getTeamAnalytics,
    getMyOrganization,
    updateSettings,
    uploadLogo,
    createCustomAlert,
    getOrgAlerts,
    assignLearningPath,
    getPathAssignments,

    assignAlertsToMembers,
    deleteCustomAlert
} = require('../controllers/organizationController');

const { checkTrialStatus } = require('../middleware/organizationMiddleware');

// All routes require authentication
router.use(protect);

// User's organization
router.get('/my', getMyOrganization);

// Organization CRUD
router.post('/', createOrganization);
router.get('/:id', getOrganization);

// Settings & Branding
router.put('/:id/settings', updateSettings);
router.post('/:id/logo', upload.single('logo'), uploadLogo);
router.post('/:id/cancel', require('../controllers/organizationController').cancelSubscription);

// Member management
router.get('/:id/members', getMembers);
router.post('/:id/invite', checkTrialStatus, inviteMember);
router.delete('/:id/members/:userId', removeMember); // Allowing removal even if expired? Yes.

// Accept invite (public-ish, but needs auth)
router.post('/invite/:token/accept', acceptInvite);

// Analytics
router.get('/:id/analytics', getTeamAnalytics);

// Custom Alerts
router.post('/:id/alerts', checkTrialStatus, createCustomAlert);
router.delete('/:id/alerts/:alertId', deleteCustomAlert);
router.post('/:id/assign-alerts', checkTrialStatus, assignAlertsToMembers);
router.get('/:id/alerts', getOrgAlerts);

// Leaderboard
router.get('/:id/leaderboard', require('../controllers/organizationController').getLeaderboard);

// Reports
const { exportTeamProgress, exportComplianceReport, exportRawData } = require('../controllers/organizationController');
// Reports are view-only, maybe allow them? Or block? Let's allow reporting for now so they can see what they did.
router.get('/:id/reports/progress', exportTeamProgress);
router.get('/:id/reports/compliance', exportComplianceReport);
router.get('/:id/reports/raw', exportRawData);

// Learning Path Assignments
router.post('/:id/assign-path', checkTrialStatus, assignLearningPath);
router.get('/:id/assignments', getPathAssignments);

module.exports = router;
