const express = require('express');
const router = express.Router();
const OnboardingController = require('../controllers/onboarding.controller');
const { authenticateToken } = require('../middleware/auth');
const { requireAdmin, canViewOnboarding } = require('../middleware/roleCheck');
const { getDepartmentManager, searchEntraUserByName } = require('../services/graph.service');
const { asyncHandler } = require('../middleware/errorHandler');

// Public: employee confirms handover via token link (no auth needed)
router.get('/confirm/:token', OnboardingController.confirmByToken);

router.use(authenticateToken);

// Entra: find manager for a department (accessible to all onboarding roles)
router.get('/entra-manager', canViewOnboarding, asyncHandler(async (req, res) => {
    const { department } = req.query;
    const manager = await getDepartmentManager(department);
    res.json({ status: 'success', data: manager });
}));

// Entra: search user by name
router.get('/entra-search', canViewOnboarding, asyncHandler(async (req, res) => {
    const { name } = req.query;
    const results = await searchEntraUserByName(name);
    res.json({ status: 'success', data: results });
}));

// Stats + read endpoints: accessible to dept roles
router.get('/stats', canViewOnboarding, OnboardingController.getStatistics);
router.get('/', canViewOnboarding, OnboardingController.getAllProtocols);
router.get('/:id', canViewOnboarding, OnboardingController.getProtocolById);

// Write endpoints: admins only
router.post('/', canViewOnboarding, OnboardingController.createProtocol);
router.put('/:id', canViewOnboarding, OnboardingController.updateProtocol); // dept roles can save checklist
router.post('/:id/send-confirmation', canViewOnboarding, OnboardingController.sendConfirmationEmail);
router.post('/:id/regenerate-pdf', requireAdmin, OnboardingController.regeneratePdf);
router.delete('/:id', canViewOnboarding, OnboardingController.deleteProtocol);

module.exports = router;
