import { Server, Session } from "@hibas123/openauth-internalapi";
import type { SessionContext } from "../index.js";
import Logging from "@hibas123/nodelogging";
import { RequireLogin } from "../../../helper/login.js";
import crypto from "node:crypto";
import User from "../../../models/user.js";

export default class SecurityService extends Server.SecurityService<SessionContext> {
   @RequireLogin()
   async GetSessions(ctx: SessionContext): Promise<Session[]> {
      return []
      throw new Error("Method not implemented.");
   }
   @RequireLogin()
   async RevokeSession(id: string, ctx: SessionContext): Promise<void> {
      throw new Error("Method not implemented.");
   }

   @RequireLogin()
   async ChangePassword(old_pw: string, new_pw: string, ctx: SessionContext): Promise<void> {
      let old_pw_hash = crypto.createHash("sha512").update(ctx.user.salt + old_pw).digest("hex");

      if (old_pw_hash != ctx.user.password) {
         throw new Error("Wrong password");
      }

      let salt = crypto.randomBytes(32).toString("base64");
      let password_hash = crypto.createHash("sha512").update(salt + new_pw).digest("hex");

      ctx.user.salt = salt;
      ctx.user.password = password_hash;

      await User.save(ctx.user);
   }
}
