import { Router, Request, Response } from 'express';
import jwt from 'jsonwebtoken';
import { env } from '../../config/env';
import { logger } from '../../utils/logger';

const router = Router();

interface SsoPayload {
  sub: string;
  giteaUser: string;
}

/**
 * GET /api/auth/gitea-sso-validate
 *
 * Called by nginx auth_request to validate the cml_session cookie.
 * Always returns 200 — never blocks requests.
 * Sets X-Gitea-User header when the session is valid and the user
 * has a provisioned Gitea account. Empty header = no SSO (Gitea
 * shows its own login page).
 */
router.get('/gitea-sso-validate', (req: Request, res: Response) => {
  const token = req.cookies?.cml_session;

  if (!token) {
    res.setHeader('X-Gitea-User', '');
    res.status(200).end();
    return;
  }

  try {
    const ssoSecret = env.GITEA_SSO_SECRET;
    const payload = jwt.verify(token, ssoSecret, {
      algorithms: ['HS256'],
    }) as SsoPayload;

    if (payload.giteaUser) {
      res.setHeader('X-Gitea-User', payload.giteaUser);
    } else {
      res.setHeader('X-Gitea-User', '');
    }
  } catch {
    // Expired or invalid JWT — no SSO, graceful fallback
    res.setHeader('X-Gitea-User', '');
  }

  res.status(200).end();
});

export { router as giteaSsoRouter };
