import { createRoute } from "../../modules/api-utils/createRoute";
import { redis } from "../../constants";

/* /v1/auth/callback/:callbackKey */
export default createRoute("get", ["/callback/:callbackKey"], async (c) => {
  const callbackKey = c.req.param("callbackKey");
  if (!callbackKey) {
    c.status(400);
    return c.json({ status: 400, message: "Missing callbackKey", successful: false });
  }

  const redisKey = `auth:cb:${callbackKey}`;
  const raw = await redis.get(redisKey);
  if (!raw) {
    c.status(202);
    return c.json({ status: 202, message: "Pending", successful: false });
  }

  // Delete immediately so tokens can't be replayed
  await redis.del(redisKey);

  const tokens = JSON.parse(raw) as { accessToken: string; refreshToken: string };
  return c.json({ status: 200, message: "Auth callback resolved", data: tokens, successful: true });
});
