import { Router, Request, Response, NextFunction } from 'express';
import { authenticate } from '../../middleware/auth.middleware';
import { requireRole } from '../../middleware/rbac.middleware';
import { registryService } from './registry.service';

const router = Router();

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

// GET /api/registry/status — list container images in Gitea registry
router.get('/status', async (_req: Request, res: Response, next: NextFunction) => {
  try {
    const images = await registryService.getRegistryStatus();
    res.json({ images });
  } catch (err) {
    next(err);
  }
});

// POST /api/registry/build-push — trigger build-and-push.sh via trigger file
router.post('/build-push', async (req: Request, res: Response, next: NextFunction) => {
  try {
    const { skipCodeServer, services } = req.body as { skipCodeServer?: boolean; services?: string };
    registryService.triggerBuildPush(req.user?.email ?? 'api', { skipCodeServer, services });
    res.json({ ok: true, message: 'Build and push triggered (runs in background)' });
  } catch (err) {
    next(err);
  }
});

// POST /api/registry/mirror — trigger mirror-images.sh via trigger file
router.post('/mirror', async (req: Request, res: Response, next: NextFunction) => {
  try {
    const { all } = req.body as { all?: boolean };
    registryService.triggerMirror(req.user?.email ?? 'api', { all });
    res.json({ ok: true, message: 'Mirror triggered (runs in background)' });
  } catch (err) {
    next(err);
  }
});

export const registryRouter = router;
