import { SignJWT, jwtVerify } from "jose";

function getSecret(): Uint8Array {
  const secret = process.env.JWT_SECRET ?? "dev-jwt-secret-change-in-production";
  return Buffer.from(secret, "utf-8");
}

export async function signJWT(
  payload: Record<string, unknown>,
  options?: { expiresIn?: string },
): Promise<string> {
  return new SignJWT(payload)
    .setProtectedHeader({ alg: "HS256" })
    .setIssuedAt()
    .setExpirationTime(options?.expiresIn ?? "7d")
    .sign(getSecret());
}

export async function verifyJWT<T = Record<string, unknown>>(
  token: string,
): Promise<T> {
  const { payload } = await jwtVerify(token, getSecret());
  return payload as T;
}
