import { Request, Response, NextFunction } from 'express';
import { logger } from '../services/logger';

/**
 * Dev-Mode Authentifizierung
 *
 * Wenn NODE_ENV=development und kein Staffbase JWT vorhanden,
 * wird automatisch ein Mock-User eingeloggt.
 *
 * Mehrere Test-User über Query-Parameter wählbar:
 *   ?devUser=1  → Ronny Mueller (du)
 *   ?devUser=2  → Test User 2
 *   ?devUser=3  → Test User 3
 *
 * Wird in Production komplett deaktiviert.
 */

const DEV_USERS = [
  {
    sub: 'dev-user-001',
    name: 'Ronny Mueller',
    given_name: 'Ronny',
    family_name: 'Mueller',
    locale: 'de_DE',
    branch_id: 'gealan-main',
    role: 'editor',
    primary_email_address: 'ronny975@gmail.com',
  },
  {
    sub: 'dev-user-002',
    name: 'Max Mustermann',
    given_name: 'Max',
    family_name: 'Mustermann',
    locale: 'de_DE',
    branch_id: 'gealan-main',
    role: 'viewer',
    primary_email_address: 'max@gealan.de',
  },
  {
    sub: 'dev-user-003',
    name: 'Anna Schmidt',
    given_name: 'Anna',
    family_name: 'Schmidt',
    locale: 'de_DE',
    branch_id: 'gealan-werk2',
    role: 'viewer',
    primary_email_address: 'anna@gealan.de',
  },
];

export const devAuth = (req: Request, res: Response, next: NextFunction): void => {
  if (process.env.NODE_ENV === 'production') {
    // In Production niemals Dev-Mode verwenden
    res.status(401).json({ error: 'Unauthorized' });
    return;
  }

  const userIndex = parseInt((req.query.devUser as string) ?? '1') - 1;
  const mockUser = DEV_USERS[Math.min(Math.max(userIndex, 0), DEV_USERS.length - 1)];

  req.staffbaseUser = mockUser;
  req.sbSSO = mockUser;

  logger.debug('Dev-Mode: Mock user injected', { user: mockUser.name });
  next();
};
