import { Password } from "@/contexts/common/domain";
import { ISequelizeMapper, SequelizeMapper } from "@/contexts/common/infrastructure";
import { Email, Language, Name, UniqueID } from "@shared/contexts";
import { IUserProps, User, UserRole } from "../../domain";
import { IUserContext } from "../User.context";
import { UserCreationAttributes, User_Model } from "../sequelize/user.model";

export interface IUserMapper extends ISequelizeMapper<User_Model, UserCreationAttributes, User> {}

class UserMapper
  extends SequelizeMapper<User_Model, UserCreationAttributes, User>
  implements IUserMapper
{
  public constructor(props: { context: IUserContext }) {
    super(props);
  }

  protected toDomainMappingImpl(source: User_Model, params: any): User {
    const props: IUserProps = {
      name: this.mapsValue(source, "name", Name.create),
      email: this.mapsValue(source, "email", Email.create),
      password: this.mapsValue(source, "password", Password.createFromHashedTextPassword),
      roles: source.roles.map((rol) => UserRole.create(rol).object),
      language: this.mapsValue(source, "language", Language.createFromCode),
    };

    const id = this.mapsValue(source, "id", UniqueID.create);
    const userOrError = User.create(props, id);

    if (userOrError.isFailure) {
      throw userOrError.error;
    }

    return userOrError.object;
  }

  protected toPersistenceMappingImpl(source: User, params?: Record<string, any> | undefined) {
    return {
      id: source.id.toPrimitive(),
      name: source.name.toPrimitive(),
      email: source.email.toPrimitive(),
      password: source.password.toPrimitive(),
      lang_code: source.language.toPrimitive(),
      roles: source.getRoles().map((rol) => rol.toPrimitive()),
    };
  }
}

export const createUserMapper = (context: IUserContext): IUserMapper =>
  new UserMapper({
    context,
  });
