import { Router, Request, Response } from 'express';
import { AuthService } from '../../services/auth.service';
import { requireAuth, AuthRequest } from '../../middleware/auth.middleware';
import { GameSettingsService } from '../../services/game-settings.service';
import rateLimit from 'express-rate-limit';
import { OAuth2Client } from 'google-auth-library';
import { ENV } from '../../config/env';

const router = Router();
const googleClient = new OAuth2Client(ENV.GOOGLE_CLIENT_ID);

async function resolveGoogleProfile(credential: string): Promise<{ id: string; email: string; name: string; picture?: string }> {
  if (!ENV.GOOGLE_CLIENT_ID) {
    throw new Error('Google OAuth non configuré');
  }

  const isJwt = credential.split('.').length === 3;

  if (isJwt) {
    const ticket = await googleClient.verifyIdToken({
      idToken: credential,
      audience: ENV.GOOGLE_CLIENT_ID,
    });
    const payload = ticket.getPayload();

    if (!payload?.sub || !payload.email) {
      throw new Error('Token Google invalide');
    }
    if (payload.email_verified === false) {
      throw new Error('Email Google non vérifié');
    }

    return {
      id: payload.sub,
      email: payload.email,
      name: payload.name || payload.email.split('@')[0],
      picture: payload.picture || undefined,
    };
  }

  const fetchAny: any = (globalThis as any).fetch;
  if (!fetchAny) {
    throw new Error('fetch indisponible');
  }

  const tokenInfoRes = await fetchAny(`https://www.googleapis.com/oauth2/v3/tokeninfo?access_token=${encodeURIComponent(credential)}`);
  if (!tokenInfoRes.ok) {
    throw new Error('Token Google invalide');
  }
  const tokenInfo = await tokenInfoRes.json() as any;
  const aud = tokenInfo.aud || tokenInfo.audience;
  if (aud && aud !== ENV.GOOGLE_CLIENT_ID) {
    throw new Error('Token Google invalide');
  }

  const userInfoRes = await fetchAny('https://www.googleapis.com/oauth2/v3/userinfo', {
    headers: { Authorization: `Bearer ${credential}` },
  });
  if (!userInfoRes.ok) {
    throw new Error('Token Google invalide');
  }
  const userInfo = await userInfoRes.json() as any;
  if (!userInfo?.sub || !userInfo.email) {
    throw new Error('Token Google invalide');
  }

  return {
    id: userInfo.sub,
    email: userInfo.email,
    name: userInfo.name || userInfo.email.split('@')[0],
    picture: userInfo.picture || undefined,
  };
}

// Rate limiting for auth routes
const authLimiter = rateLimit({
  windowMs: 15 * 60 * 1000, // 15 minutes
  max: 20,
  message: { error: 'Trop de tentatives, réessayez dans 15 minutes' },
});

/**
 * POST /auth/register
 * Create new account with email/password
 */
router.post('/register', authLimiter, async (req: Request, res: Response) => {
  try {
    const { username, email, password, language, newsletter_optin } = req.body;

    if (!username || !email || !password) {
      return res.status(400).json({ error: 'Tous les champs sont requis' });
    }

    const result = await AuthService.register({
      username, email, password, language, newsletter_optin,
    });

    res.status(201).json(result);
  } catch (err: any) {
    res.status(400).json({ error: err.message });
  }
});

/**
 * POST /auth/login
 * Login with email/password
 */
router.post('/login', authLimiter, async (req: Request, res: Response) => {
  try {
    const { email, password } = req.body;

    if (!email || !password) {
      return res.status(400).json({ error: 'Email et mot de passe requis' });
    }

    const result = await AuthService.login({ email, password });
    res.json(result);
  } catch (err: any) {
    res.status(401).json({ error: err.message });
  }
});

/**
 * POST /auth/oauth/:provider
 * OAuth login (google, facebook)
 */
router.post('/oauth/:provider', authLimiter, async (req: Request, res: Response) => {
  try {
    const provider = req.params.provider as 'google' | 'facebook';

    if (!['google', 'facebook'].includes(provider)) {
      return res.status(400).json({ error: 'Provider non supporté' });
    }

    // Guard: vérifier si le provider OAuth est activé en admin
    const providerEnabled = await GameSettingsService.get<boolean>(
      `auth.${provider}_enabled`,
      provider === 'google' // Google activé par défaut, Facebook non
    );
    if (!providerEnabled) {
      return res.status(503).json({ error: `Connexion via ${provider} non disponible actuellement` });
    }

    if (provider === 'google') {
      const { credential } = req.body as any;
      if (!credential || typeof credential !== 'string') {
        return res.status(400).json({ error: 'Token Google requis' });
      }
      const profile = await resolveGoogleProfile(credential);
      const result = await AuthService.oauthLogin('google', profile);
      return res.json(result);
    }

    return res.status(503).json({ error: 'Connexion via Facebook non disponible' });
  } catch (err: any) {
    res.status(400).json({ error: err.message });
  }
});

/**
 * GET /auth/profile
 * Get current authenticated player profile
 */
router.get('/profile', requireAuth, async (req: AuthRequest, res: Response) => {
  try {
    const profile = await AuthService.getProfile(req.playerId!);
    res.json(profile);
  } catch (err: any) {
    res.status(404).json({ error: err.message });
  }
});

/**
 * POST /auth/logout
 * Logout (client-side token removal, server-side optional blacklist)
 */
router.post('/logout', requireAuth, (_req: AuthRequest, res: Response) => {
  // JWT is stateless; client removes token
  // Future: add token to Redis blacklist
  res.json({ message: 'Déconnexion réussie' });
});

/**
 * POST /auth/refresh-token
 * Refresh JWT access token
 */
router.post('/refresh-token', async (req: Request, res: Response) => {
  try {
    const { refreshToken } = req.body;
    if (!refreshToken) {
      return res.status(400).json({ error: 'Refresh token requis' });
    }
    const tokens = await AuthService.refreshToken(refreshToken);
    res.json(tokens);
  } catch (err: any) {
    res.status(401).json({ error: err.message });
  }
});

/**
 * POST /auth/password-reset
 * Request password reset email
 */
router.post('/password-reset', authLimiter, async (req: Request, res: Response) => {
  try {
    const { email } = req.body;
    if (!email) {
      return res.status(400).json({ error: 'Email requis' });
    }
    await AuthService.requestPasswordReset(email);
    res.json({ message: 'Si un compte existe avec cet email, un lien de réinitialisation a été envoyé' });
  } catch (err: any) {
    res.status(500).json({ error: err.message });
  }
});

/**
 * POST /auth/password-reset/confirm
 * Reset password with token
 */
router.post('/password-reset/confirm', authLimiter, async (req: Request, res: Response) => {
  try {
    const { token, newPassword } = req.body;
    if (!token || !newPassword) {
      return res.status(400).json({ error: 'Token et nouveau mot de passe requis' });
    }
    await AuthService.confirmPasswordReset(token, newPassword);
    res.json({ message: 'Mot de passe réinitialisé avec succès' });
  } catch (err: any) {
    res.status(400).json({ error: err.message });
  }
});

export default router;
