import { eq } from "drizzle-orm";
import db from "~/drizzle";
import { discordTokens } from "~/drizzle/schema";
import { discord } from "./auth";

const getAccessToken = async (userId: string) => {
  let tokens = await db.query.discordTokens
    .findFirst({
      where: eq(discordTokens.userId, userId),
    })
    .execute();

  if (tokens && new Date() >= tokens.expiresAt) {
    const newTokens = await discord.refreshAccessToken(tokens.refreshToken);

    tokens = (
      await db
        .update(discordTokens)
        .set({
          accessToken: newTokens.accessToken,
          expiresAt: newTokens.accessTokenExpiresAt,
          refreshToken: newTokens.refreshToken,
        })
        .where(eq(discordTokens.userId, userId))
        .returning()
        .execute()
    )[0];
  }

  if (!tokens) return tokens;
  return tokens;
};

export default getAccessToken;
