// FILE: backend/src/utils/jwt.js
import jwt from "jsonwebtoken";

const ACCESS_SECRET = process.env.JWT_ACCESS_SECRET || "dev_access_secret";
const REFRESH_SECRET = process.env.JWT_REFRESH_SECRET || "dev_refresh_secret";

export const ACCESS_TTL_MS = parseInt(
  process.env.ACCESS_TTL_MS || `${15 * 60 * 1000}`,
  10
); // 15 นาที
export const REFRESH_TTL_MS = parseInt(
  process.env.REFRESH_TTL_MS || `${7 * 24 * 60 * 60 * 1000}`,
  10
); // 7 วัน

export function signAccessToken(payload) {
  return jwt.sign(payload, ACCESS_SECRET, {
    expiresIn: Math.floor(ACCESS_TTL_MS / 1000),
  });
}
export function signRefreshToken(payload) {
  return jwt.sign(payload, REFRESH_SECRET, {
    expiresIn: Math.floor(REFRESH_TTL_MS / 1000),
  });
}
export function verifyAccessToken(token) {
  return jwt.verify(token, ACCESS_SECRET, { clockTolerance: 10 }); // เผื่อเวลา QNAP คลาด
}
export function verifyRefreshToken(token) {
  return jwt.verify(token, REFRESH_SECRET, { clockTolerance: 10 });
}
