import { ISequelizeAdapter, SequelizeRepository } from "@/contexts/common/infrastructure/sequelize";
import { Email, ICollection, IQueryCriteria, Name, UniqueID } from "@shared/contexts";
import { Op, Transaction } from "sequelize";
import { User } from "../domain";
import { IUserRepository } from "../domain/repository";
import { IUserContext } from "./User.context";
import { IUserMapper, createUserMapper } from "./mappers";

export type QueryParams = {
  pagination: Record<string, any>;
  filters: Record<string, any>;
};

export class UserRepository extends SequelizeRepository<User> implements IUserRepository {
  protected mapper: IUserMapper;

  public constructor(props: {
    mapper: IUserMapper;
    adapter: ISequelizeAdapter;
    transaction: Transaction;
  }) {
    const { adapter, mapper, transaction } = props;
    super({ adapter, transaction });
    this.mapper = mapper;
  }

  public async create(user: User): Promise<void> {
    const userData = this.mapper.mapToPersistence(user);
    await this._save("User_Model", user.id, userData);
  }

  public async update(user: User): Promise<void> {
    const userData = this.mapper.mapToPersistence(user);

    // borrando y luego creando
    // await this.removeById(user.id, true);
    await this._save("User_Model", user.id, userData, {});
  }

  public async getById(id: UniqueID): Promise<User | null> {
    const rawUser: any = await this._getById("User_Model", id);

    if (!rawUser === true) {
      return null;
    }

    return this.mapper.mapToDomain(rawUser);
  }

  public async findUserByEmail(email: Email): Promise<User | null> {
    const rawUser: any = await this._getBy("User_Model", "email", email.toPrimitive());

    if (!rawUser === true) {
      return null;
    }

    return this.mapper.mapToDomain(rawUser);
  }

  public async findAll(queryCriteria?: IQueryCriteria): Promise<ICollection<any>> {
    const { rows, count } = await this._findAll(
      "User_Model",
      queryCriteria
      /*{
        include: [],  // esto es para quitar las asociaciones al hacer la consulta
      }*/
    );

    return this.mapper.mapArrayAndCountToDomain(rows, count);
  }

  public async removeById(id: UniqueID, force: boolean = false): Promise<void> {
    return this._removeById("User_Model", id);
  }

  public async existsAdminUser(): Promise<boolean> {
    const _model = this._adapter.getModel("User_Model");

    // Verificar si el usuario administrador existe
    const count: number = await _model.count({
      where: { roles: { [Op.like]: ["%ROLE_ADMIN%"] } },
      transaction: this._transaction,
    });

    return Promise.resolve(Boolean(count !== 0));
  }

  public async existsUserWithId(id: UniqueID): Promise<boolean> {
    return this._exists("User_Model", "id", id.toPrimitive());
  }

  public async existsUserWithName(name: Name): Promise<boolean> {
    return this._exists("User_Model", "name", name.toPrimitive());
  }

  public async existsUserWithEmail(email: Email): Promise<boolean> {
    return this._exists("User_Model", "email", email.toPrimitive());
  }
}

export const registerUserRepository = (context: IUserContext) => {
  const adapter = context.adapter;
  const repoManager = context.repositoryManager;

  repoManager.registerRepository("User", (params = { transaction: null }) => {
    const { transaction } = params;

    return new UserRepository({
      transaction,
      adapter,
      mapper: createUserMapper(context),
    });
  });
};
