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

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

export async 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);
    const user = await prisma.user.findUnique({ where: { id: payload.userId } });
    if (!user || !user.active) return res.status(401).json({ message: "РџРѕР»СЊР·РѕРІР°С‚РµР»СЊ РЅРµРґРѕСЃС‚СѓРїРµРЅ" });

    req.user = { id: user.id, role: user.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();
}
