import jwt from 'jsonwebtoken';
import bcrypt from 'bcryptjs';

const JWT_SECRET = "xK4-pQ9mR2vL7wZn.Yb3jF8hT5dN1cS6";
function signToken(payload) {
  return jwt.sign(payload, JWT_SECRET, { expiresIn: "7d" });
}
function verifyToken(token) {
  try {
    return jwt.verify(token, JWT_SECRET);
  } catch {
    return null;
  }
}
function parseCookies(cookieHeader) {
  if (!cookieHeader) return {};
  return Object.fromEntries(
    cookieHeader.split(";").map((c) => {
      const [key, ...val] = c.trim().split("=");
      return [key, val.join("=")];
    })
  );
}
function getTokenFromRequest(request) {
  const authHeader = request.headers.get("Authorization");
  if (authHeader?.startsWith("Bearer ")) return authHeader.slice(7);
  const cookies = parseCookies(request.headers.get("cookie"));
  return cookies.admin_token || null;
}
async function comparePassword(password, hash) {
  return bcrypt.compare(password, hash);
}

export { comparePassword as c, getTokenFromRequest as g, parseCookies as p, signToken as s, verifyToken as v };
