import { Request, Response, NextFunction } from 'express';
import jwt from 'jsonwebtoken';
import Admin from '../models/admin';
import { sendResponse } from '../utils/apiResponse';

const protectAdmin = async (req: Request, res: Response, next: NextFunction): Promise<void> => {
  try {
    let token: string | undefined;
    if (req.headers.authorization?.startsWith('Bearer')) {
      token = req.headers.authorization.split(' ')[1];
    }

    if (!token) {
      sendResponse(res, 401, 'Not authorized, no token');
      return;
    }

    const decoded = jwt.verify(token, process.env.JWT_SECRET!) as { id: string; tokenVersion: number };
    const admin = await Admin.findById(decoded.id);

    if (!admin) {
      sendResponse(res, 403, 'Access denied. Admins only.');
      return;
    }

    if (decoded.tokenVersion !== admin.tokenVersion) {
      sendResponse(res, 401, 'Session expired. Please log in again.');
      return;
    }

    req.admin = admin;
    next();
  } catch {
    sendResponse(res, 401, 'Not authorized, invalid token');
  }
};

export default protectAdmin;
