const express = require('express');
const router = express.Router();
const { authenticateToken, authorizePermission } = require('../middleware/auth');
const Organization = require('../models/Organization');
const OrganizationController = require('../controllers/organizationController');
const { validateOrganizationCreation, validateOrganizationUpdate, validateOrganizationId } = require('../middleware/organizationValidation');
const { createOptionalImageUploadMiddleware } = require('../middleware/fileUpload');
// All routes require authentication
router.use(authenticateToken);
// GET /api/organizations/my-organization - Get current user's organization (no permission check needed)
router.get('/my-organization', async (req, res, next) => {
    try {
        const userOrgId = req.user && req.user.organization_id ? parseInt(req.user.organization_id, 10) : null;
        let organization = null;
        if (userOrgId) {
            organization = await Organization.findById(userOrgId);
        }
        else {
            try {
                const result = await Organization.findAll({ limit: 1, is_active: 'true' });
                organization = (result && result.data && result.data.length > 0) ? result.data[0] : null;
            }
            catch (e) {
                organization = null;
            }
        }
        if (!organization) {
            return res.status(200).json({
                status: 'success',
                message: 'No organization configured for user',
                data: { organization: null }
            });
        }
        const orgWithLogo = OrganizationController.addLogoUrl(req, organization) || (typeof organization.toJSON === 'function' ? organization.toJSON() : organization);
        return res.status(200).json({
            status: 'success',
            message: 'Organization retrieved successfully',
            data: { organization: orgWithLogo }
        });
    }
    catch (error) {
        next(error);
    }
});
// GET /api/organizations/statistics - Get organization statistics
router.get('/statistics', authorizePermission('organization.read'), OrganizationController.getStatistics);
// GET /api/organizations/types - Get organization types
router.get('/types', authorizePermission('organization.read'), OrganizationController.getTypes);
// GET /api/organizations - Get all organizations
router.get('/', async (req, res, next) => {
    try {
        if (isSuperAdmin(req.user)) {
            return OrganizationController.getOrganizations(req, res, next);
        }
        return authorizePermission('organization.read')(req, res, (err) => {
            if (err)
                return next(err);
            return OrganizationController.getOrganizations(req, res, next);
        });
    }
    catch (error) {
        next(error);
    }
});
// Helper: detect super admin
const isSuperAdmin = (user) => {
    if (!user)
        return false;
    const roleName = (user.role || '').toLowerCase();
    return user.role_id === 1 || roleName === 'super admin' || roleName === 'super_admin';
};
// GET /api/organizations/:id - Get specific organization
// Rule: Super Admin -> any ID; others -> only own organization ID without needing permission
router.get('/:id', validateOrganizationId, async (req, res, next) => {
    try {
        if (isSuperAdmin(req.user)) {
            return OrganizationController.getOrganizationById(req, res, next);
        }
        const requestedId = parseInt(req.params.id);
        const userOrgId = req.user && parseInt(req.user.organization_id);
        if (userOrgId && requestedId === userOrgId) {
            // Allow own organization without extra permission
            return OrganizationController.getOrganizationById(req, res, next);
        }
        // Otherwise, require permission
        return authorizePermission('organization.read')(req, res, (err) => {
            if (err)
                return next(err);
            return OrganizationController.getOrganizationById(req, res, next);
        });
    }
    catch (error) {
        next(error);
    }
});
// POST /api/organizations - Create new organization
router.post('/', authorizePermission('organization.create'), createOptionalImageUploadMiddleware('logo', 'organization'), // Logo upload middleware
validateOrganizationCreation, OrganizationController.createOrganization);
// PUT /api/organizations/:id - Update organization
router.put('/:id', authorizePermission('organization.update'), createOptionalImageUploadMiddleware('logo', 'organization'), // Logo upload middleware
validateOrganizationUpdate, OrganizationController.updateOrganization);
// DELETE /api/organizations/:id - Delete organization
router.delete('/:id', authorizePermission('organization.delete'), validateOrganizationId, OrganizationController.deleteOrganization);
module.exports = router;
//# sourceMappingURL=organizations.js.map