import express from "express";
import { getAdminStats } from "../controllers/adminStats.js";
import jwt from "jsonwebtoken";
import { User } from "../models/usermodels.js";

const router = express.Router();

// Simple admin auth middleware
const adminAuth = async (req, res, next) => {
  try {
    let token = req.cookies?.token;
    if (!token) {
      const h = req.headers.authorization;
      if (h?.startsWith("Bearer ")) token = h.split(" ")[1];
    }
    if (!token) return res.status(401).json({ message: "Unauthorized" });

    const decoded = jwt.verify(token, process.env.JWT_SECRET);
    const user = await User.findById(decoded.id);
    if (!user) return res.status(401).json({ message: "User not found" });

    // Optional: check user.role === "admin" if you have roles
    req.user = user;
    next();
  } catch (err) {
    return res.status(401).json({ message: "Invalid token" });
  }
};

router.get("/stats", adminAuth, getAdminStats);

export default router;