import jwt from "jsonwebtoken";
import { accessTokenPrivateKey, prisma } from "../src/constants";

await (async () => {
  const userIdentifier = Bun.argv[2]?.trim();

  if (Bun.argv.length !== 3 || !userIdentifier) {
    console.error(
      "1 argument expected.\nFormat: bun run utils:gen_access_token {user_identifier}"
    );
    process.exit(1);
  }

  const user = await prisma.user.findFirst({
    where: {
      OR: [
        { id: userIdentifier },
        { login: userIdentifier },
        { email: userIdentifier },
        { userId: userIdentifier },
      ],
    },
  });

  if (!user) {
    console.error(`User with identifier '${userIdentifier}' doesn't exist.`);
    process.exit(1);
  }

  // A backing session is required because access-token validation resolves by sessionKey.
  const session = await prisma.session.create({
    data: {
      userId: user.id,
      expires: new Date(Date.now() + 24 * 60 * 60 * 1000),
    },
  });

  const token = jwt.sign(
    {
      sessionKey: session.sessionKey,
      userID: user.id,
    },
    accessTokenPrivateKey,
    {
      algorithm: "RS256",
      expiresIn: "24h",
    }
  );

  console.log(token);
  process.exit(0);
})();