import { Router, Request, Response, NextFunction } from 'express';
import { z } from 'zod';
import { authenticate } from '../../middleware/auth.middleware';
import { requireNonTemp, requireRole } from '../../middleware/rbac.middleware';
import { logger } from '../../utils/logger';
import { giteaSetupService } from './gitea-setup.service';

const router = Router();
router.use(authenticate);
router.use(requireNonTemp);
router.use(requireRole('SUPER_ADMIN'));

const credentialsSchema = z.object({
  username: z.string().min(1).max(100),
  password: z.string().min(1).max(200),
});

// GET /api/gitea/setup/status — check current setup state
router.get(
  '/status',
  async (_req: Request, res: Response, next: NextFunction) => {
    try {
      const status = await giteaSetupService.checkStatus();
      res.json(status);
    } catch (err) {
      logger.error('Failed to check Gitea setup status', err);
      next(err);
    }
  },
);

// POST /api/gitea/setup/test-connection — test basic auth credentials
router.post(
  '/test-connection',
  async (req: Request, res: Response, next: NextFunction) => {
    try {
      const parsed = credentialsSchema.safeParse(req.body);
      if (!parsed.success) {
        res.status(400).json({ error: { message: 'Username and password required', code: 'VALIDATION_ERROR' } });
        return;
      }
      const result = await giteaSetupService.testConnection(parsed.data.username, parsed.data.password);
      res.json(result);
    } catch (err) {
      logger.error('Failed to test Gitea connection', err);
      next(err);
    }
  },
);

// POST /api/gitea/setup/run — run full setup
router.post(
  '/run',
  async (req: Request, res: Response, next: NextFunction) => {
    try {
      const parsed = credentialsSchema.safeParse(req.body);
      if (!parsed.success) {
        res.status(400).json({ error: { message: 'Username and password required', code: 'VALIDATION_ERROR' } });
        return;
      }
      const result = await giteaSetupService.runFullSetup(parsed.data.username, parsed.data.password);
      res.json(result);
    } catch (err) {
      logger.error('Failed to run Gitea setup', err);
      next(err);
    }
  },
);

export const giteaSetupRouter = router;
