import DB from "../database.js";
import { ModelDataBase } from "@hibas123/safe_mongo/lib/model.js";
import { ObjectId } from "mongodb";
import moment = require("moment");

export interface ILoginToken extends ModelDataBase {
   token: string;
   special: boolean;
   user: ObjectId;
   validTill: Date;
   valid: boolean;
   validated: boolean;
   data: any;
   ip: string;
   browser: string;
}
const LoginToken = DB.addModel<ILoginToken>({
   name: "login_token",
   versions: [
      {
         migration: () => { },
         schema: {
            token: { type: String },
            special: { type: Boolean, default: () => false },
            user: { type: ObjectId },
            validTill: { type: Date },
            valid: { type: Boolean },
         },
      },
      {
         migration: (doc: ILoginToken) => {
            doc.validated = true;
         },
         schema: {
            token: { type: String },
            special: { type: Boolean, default: () => false },
            user: { type: ObjectId },
            validTill: { type: Date },
            valid: { type: Boolean },
            validated: { type: Boolean, default: false },
         },
      },
      {
         migration: (doc: ILoginToken) => {
            doc.validated = true;
         },
         schema: {
            token: { type: String },
            special: { type: Boolean, default: () => false },
            user: { type: ObjectId },
            validTill: { type: Date },
            valid: { type: Boolean },
            validated: { type: Boolean, default: false },
            data: { type: "any", optional: true },
            ip: { type: String, optional: true },
            browser: { type: String, optional: true },
         },
      },
   ],
});

export async function CheckToken(
   token: ILoginToken,
   validated: boolean = true
): Promise<boolean> {
   if (!token || !token.valid) return false;
   if (validated && !token.validated) return false;
   if (moment().isAfter(token.validTill)) {
      token.valid = false;
      await LoginToken.save(token);
      return false;
   }
   return true;
}

export default LoginToken;
