import { Profile, ContactInfo, Gender, Server, UserRegisterInfo } from "@hibas123/openauth-internalapi";
import type { SessionContext } from "../index.js";
import Mail from "../../../models/mail.js";
import User from "../../../models/user.js";
import { RequireLogin } from "../../../helper/login.js";

export default class AccountService extends Server.AccountService<SessionContext> {
   Register(regcode: string, info: UserRegisterInfo, ctx: SessionContext): Promise<void> {
      throw new Error("Method not implemented.");
   }

   @RequireLogin()
   async GetProfile(ctx: SessionContext): Promise<Profile> {
      if (!ctx.user) throw new Error("Not logged in");


      return {
         id: ctx.user.uid,
         username: ctx.user.username,
         name: ctx.user.name,
         birthday: ctx.user.birthday?.valueOf(),
         gender: ctx.user.gender as number as Gender,
      }
   }

   @RequireLogin()
   async UpdateProfile(info: Profile, ctx: SessionContext): Promise<void> {
      if (!ctx.user) throw new Error("Not logged in");

      ctx.user.name = info.name;
      ctx.user.birthday = new Date(info.birthday);
      ctx.user.gender = info.gender as number;

      await User.save(ctx.user);
   }

   @RequireLogin()
   async GetContactInfos(ctx: SessionContext): Promise<ContactInfo> {
      if (!ctx.user) throw new Error("Not logged in");

      let mails = await Promise.all(
         ctx.user.mails.map((mail) => Mail.findById(mail))
      );

      let contact = {
         mail: mails.filter((e) => !!e),
         phone: ctx.user.phones,
      };

      return contact;
   }
}
