import { IUser, Gender } from "../models/user.js";
import { ObjectId } from "bson";
import { createJWT } from "../keys.js";
import { IClient } from "../models/client.js";
import config from "../config.js";
import moment = require("moment");

export interface OAuthJWT {
   user: string;
   username: string;
   permissions: string[];
   application: string;
}

const issuer = config.core.url;

export const IDTokenJWTExp = moment.duration(30, "m").asSeconds();
export function getIDToken(user: IUser, client_id: string, nonce: string) {
   return createJWT(
      {
         user: user.uid,
         name: user.name,
         nickname: user.username,
         username: user.username,
         preferred_username: user.username,
         gender: Gender[user.gender],
         nonce,
      },
      {
         expiresIn: IDTokenJWTExp,
         issuer,
         algorithm: "RS256",
         subject: user.uid,
         audience: client_id,
      }
   );
}

export const AccessTokenJWTExp = moment.duration(6, "h");
export function getAccessTokenJWT(token: {
   user: IUser;
   permissions: ObjectId[];
   client: IClient;
}) {
   return createJWT(
      <OAuthJWT>{
         user: token.user.uid,
         username: token.user.username,
         permissions: token.permissions.map((p) => p.toHexString()),
         application: token.client.client_id,
      },
      {
         expiresIn: AccessTokenJWTExp.asSeconds(),
         issuer,
         algorithm: "RS256",
         subject: token.user.uid,
         audience: token.client.client_id,
      }
   );
}
