import { NextFunction, Request, Response } from "express";
import { verifyToken } from "../lib/auth.js";

export type AuthenticatedRequest = Request & {
  user?: {
    id: string;
    role: "admin" | "user";
    email?: string | null;
  };
};

export function requireAuth(req: AuthenticatedRequest, res: Response, next: NextFunction) {
  const header = req.headers.authorization;
  const bearerToken = header?.startsWith("Bearer ") ? header.slice(7) : undefined;
  const cookieToken = typeof req.cookies?.auth_token === "string" ? req.cookies.auth_token : undefined;
  const token = bearerToken || cookieToken;

  if (!token) {
    return res.status(401).json({ message: "Требуется авторизация" });
  }

  try {
    const payload = verifyToken(token);
    req.user = {
      id: payload.userId,
      role: payload.role
    };
    next();
  } catch {
    return res.status(401).json({ message: "Невалидный токен" });
  }
}

export function requireAdmin(req: AuthenticatedRequest, res: Response, next: NextFunction) {
  if (req.user?.role !== "admin") {
    return res.status(403).json({ message: "Требуются права администратора" });
  }

  next();
}
