import { Response, NextFunction } from 'express';
import { AuthRequest } from './types';
import { extractToken } from './extractToken';
import { validateToken } from './validateToken';
import { getUser } from './getUser';

export async function auth(req: AuthRequest, res: Response, next: NextFunction)  {
  try {
    const token = extractToken(req);
    if (!token) {
      res.status(401).json({ error: 'No token provided' });
      return
    }

    const payload = validateToken(token);
    if (!payload) {
      res.status(401).json({ error: 'Invalid token' });
      return
    }

    const user = await getUser(payload.id);
    if (!user) {
      res.status(401).json({ error: 'User not found' });
      return
    }

    req.user = user;
    next();
  } catch  {
    res.status(401).json({ error: 'Authentication failed' });
  }
}