import { inject, injectable } from "inversify";
import { IUserInfo } from "./model";
import { jwtDecode } from "jwt-decode";
import { TYPES } from "../../infrastructure/ioc/types";
import { shellApi } from "../../api/api";

export abstract class UserInfoBackendAdapter {
  abstract getUserInfo(): Promise<IUserInfo>;
}
@injectable()
export class GetUserInfoBackendAdapter implements UserInfoBackendAdapter {
  constructor(@inject(TYPES.primaryApi) private api: typeof shellApi) {}
  getUserInfo(): Promise<IUserInfo> {
    const decodedToken = jwtDecode(this.api.tokenManager.getToken());
    const userInfo: IUserInfo = {
      userId: this.getUserId(decodedToken.access_info),
      firstName: decodedToken.access_info.trace_user_given_name,
      familyName: decodedToken.access_info.trace_user_family_name,
      lastName: decodedToken.access_info.trace_user_last_name,
      registrationNumber: decodedToken.access_info.identifier.find(
        (id: { type: string; value: string }) => id.type === "NUMCOL",
      )?.value,
      workCenter: decodedToken.access_info.center_code,
      role: decodedToken.access_info.role_type,
      speciality: decodedToken.access_info.professional_category,
    };
    return Promise.resolve(userInfo);
  }

  getUserId(access_info) {
    return (
      access_info.identifier?.find(
        (identifierItem: { type: string; value: string }) => identifierItem.type === "DNI",
      )?.value ||
      access_info.identifier?.find(
        (identifierItem: { type: string; value: string }) => identifierItem.type === "NIE",
      )?.value
    );
  }
}
