import { Hono } from "hono/tiny";
import { createRoute } from "../../modules/api-utils/createRoute";
import * as msal from "@azure/msal-node";
import { API_BASE_URL, msalClient, redis } from "../../constants";
import { users } from "../../managers/users";

const AUTH_CALLBACK_TTL_SECONDS = 300; // 5 minutes

/* /v1/auth/redirect */
export default createRoute("get", ["/redirect"], async (c) => {
  c.status(200);

  const tokenRequest: msal.AuthorizationCodeRequest = {
    code: c.req.query().code as string,
    scopes: ["user.read"],
    redirectUri: `${API_BASE_URL}/v1/auth/redirect`,
  };

  const authResult = await msalClient.acquireTokenByCode(tokenRequest);
  const callbackKey = c.req.query().state as string;
  const tokens = await users.authenticate(authResult);

  // Store tokens in Redis so the UI can poll for them
  await redis.set(
    `auth:cb:${callbackKey}`,
    JSON.stringify({ accessToken: tokens.accessToken, refreshToken: tokens.refreshToken }),
    "EX",
    AUTH_CALLBACK_TTL_SECONDS,
  );

  // Close the window because duh
  return c.html(
    `<script>
      window.close();
    </script>`,
  );
});
