import { Router, Request, Response, NextFunction } from 'express';
import { AuthController } from '../controllers/auth.controller';
import { authenticateToken } from '../middlewares/auth.middleware';
import { validateBody } from '../middlewares/validate.middleware';
import { ssoCallbackSchema, refreshTokenSchema, tokenExchangeSchema, passwordLoginSchema } from '../validators/auth.validator';
import { asyncHandler } from '../middlewares/errorHandler.middleware';

const router = Router();
const authController = new AuthController();

// Username/Password login endpoint (no authentication required) - for direct API access
router.post('/login', 
  validateBody(passwordLoginSchema),
  asyncHandler(authController.login.bind(authController))
);

// Token exchange endpoint (no authentication required) - for localhost development
router.post('/token-exchange', 
  validateBody(tokenExchangeSchema),
  asyncHandler(authController.exchangeToken.bind(authController))
);

// Tanflow token exchange endpoint (no authentication required)
router.post('/tanflow/token-exchange', 
  validateBody(tokenExchangeSchema),
  asyncHandler(authController.exchangeTanflowToken.bind(authController))
);

// Tanflow token refresh endpoint (no authentication required)
router.post('/tanflow/refresh',
  validateBody(refreshTokenSchema),
  asyncHandler(authController.refreshTanflowToken.bind(authController))
);

// SSO callback endpoint (no authentication required)
router.post('/sso-callback', 
  validateBody(ssoCallbackSchema),
  asyncHandler(authController.handleSSOCallback.bind(authController))
);

// Token refresh endpoint (no authentication required)
router.post('/refresh',
  validateBody(refreshTokenSchema),
  asyncHandler(authController.refreshToken.bind(authController))
);

// Protected routes (require authentication)
router.get('/me', 
  authenticateToken,
  asyncHandler(authController.getCurrentUser.bind(authController))
);

router.get('/validate',
  authenticateToken,
  asyncHandler(authController.validateToken.bind(authController))
);

// Logout endpoint - allow without authentication to clear cookies
// If token exists, validate it; if not, still clear cookies
router.post('/logout', 
  asyncHandler(async (req: Request, res: Response, next: NextFunction) => {
    // Try to authenticate if token exists
    const authHeader = req.headers.authorization;
    const token = authHeader && authHeader.split(' ')[1];
    const cookieToken = req.cookies?.accessToken;
    
    // If we have a token (header or cookie), try to authenticate
    if (token || cookieToken) {
      return authenticateToken(req, res, next);
    }
    
    // If no token, proceed anyway (logout should work even without auth)
    // This allows clearing cookies even if token is expired/invalid
    next();
  }),
  asyncHandler(authController.logout.bind(authController))
);

export default router;
