import { Router, Request, Response, NextFunction } from 'express';
import { authenticate } from '../../middleware/auth.middleware';
import { requireRole } from '../../middleware/rbac.middleware';
import { userProvisioningService } from '../../services/user-provisioning/provisioning.service';

const router = Router();

router.use(authenticate);
router.use(requireRole('SUPER_ADMIN'));

// POST /api/users/provisioning/sync — bulk sync all users (static route BEFORE :id params)
router.post(
  '/provisioning/sync',
  async (_req: Request, res: Response, next: NextFunction) => {
    try {
      const result = await userProvisioningService.bulkSync();
      res.json(result);
    } catch (err) {
      next(err);
    }
  },
);

// GET /api/users/:id/provisioning — status across all services
router.get(
  '/:id/provisioning',
  async (req: Request, res: Response, next: NextFunction) => {
    try {
      const id = req.params.id as string;
      const statuses = await userProvisioningService.getProvisioningStatus(id);
      res.json({ services: statuses });
    } catch (err) {
      next(err);
    }
  },
);

// POST /api/users/:id/provisioning/provision-all — provision to all enabled services at once
router.post(
  '/:id/provisioning/provision-all',
  async (req: Request, res: Response, next: NextFunction) => {
    try {
      const id = req.params.id as string;
      const result = await userProvisioningService.provisionAll(id);
      res.json(result);
    } catch (err) {
      next(err);
    }
  },
);

// POST /api/users/:id/provisioning/:service — provision to specific service
router.post(
  '/:id/provisioning/:service',
  async (req: Request, res: Response, next: NextFunction) => {
    try {
      const id = req.params.id as string;
      const service = req.params.service as string;
      const result = await userProvisioningService.provisionForService(id, service);
      if (!result.success) {
        res.status(400).json({ error: { message: result.error, code: 'PROVISIONING_FAILED' } });
        return;
      }
      res.json({ message: `User provisioned to ${service}`, userId: id });
    } catch (err) {
      next(err);
    }
  },
);

// DELETE /api/users/:id/provisioning/:service — deprovision from service
router.delete(
  '/:id/provisioning/:service',
  async (req: Request, res: Response, next: NextFunction) => {
    try {
      const id = req.params.id as string;
      const service = req.params.service as string;
      const result = await userProvisioningService.deprovisionFromService(id, service);
      if (!result.success) {
        res.status(400).json({ error: { message: result.error, code: 'DEPROVISION_FAILED' } });
        return;
      }
      res.json({ message: `User deprovisioned from ${service}`, userId: id });
    } catch (err) {
      next(err);
    }
  },
);

export { router as provisioningRouter };
