import { Router, Request, Response, NextFunction } from 'express';
import passport from '../lib/passport.js';
import { isAuthenticated } from '../middleware/auth.js';

const router = Router();

/**
 * POST /api/auth/login
 * Login with email and password
 */
router.post('/login', (req: Request, res: Response, next: NextFunction) => {
  passport.authenticate('local', (err: any, user: any, info: any) => {
    if (err) {
      return res.status(500).json({ error: 'Internal server error', message: err.message });
    }

    if (!user) {
      return res.status(401).json({ 
        error: 'Authentication failed', 
        message: info?.message || 'Invalid credentials' 
      });
    }

    req.logIn(user, (err) => {
      if (err) {
        return res.status(500).json({ error: 'Login failed', message: err.message });
      }

      // Return user data without sensitive fields
      const { passwordHash, ...userWithoutPassword } = user;
      res.json({ 
        message: 'Login successful', 
        user: userWithoutPassword 
      });
    });
  })(req, res, next);
});

/**
 * POST /api/auth/logout
 * Logout current user
 */
router.post('/logout', (req: Request, res: Response) => {
  req.logout((err) => {
    if (err) {
      return res.status(500).json({ error: 'Logout failed', message: err.message });
    }
    res.json({ message: 'Logout successful' });
  });
});

/**
 * GET /api/auth/me
 * Get current authenticated user
 */
router.get('/me', isAuthenticated, (req: Request, res: Response) => {
  if (!req.user) {
    return res.status(401).json({ error: 'Not authenticated' });
  }

  // Return user data without sensitive fields
  const user = req.user as any;
  const { passwordHash, ...userWithoutPassword } = user;
  res.json({ user: userWithoutPassword });
});

/**
 * GET /api/auth/check
 * Check if user is authenticated (public endpoint)
 */
router.get('/check', (req: Request, res: Response) => {
  if (req.isAuthenticated() && req.user) {
    const user = req.user as any;
    const { passwordHash, ...userWithoutPassword } = user;
    res.json({ authenticated: true, user: userWithoutPassword });
  } else {
    res.json({ authenticated: false, user: null });
  }
});

export default router;

