import { EmailAddress, UniqueID } from "@/core/common/domain";
import { SequelizeRepository } from "@/core/common/infrastructure";
import { Collection, Result } from "@repo/rdx-utils";
import { Transaction } from "sequelize";
import { Contact, IContactRepository } from "../../domain";
import { IContactMapper, contactMapper } from "../mappers";
import { ContactModel } from "./contact.model";

class ContactRepository extends SequelizeRepository<Contact> implements IContactRepository {
  private readonly _mapper!: IContactMapper;

  /**
   * 🔹 Función personalizada para mapear errores de unicidad en autenticación
   */
  private _customErrorMapper(error: Error): string | null {
    if (error.name === "SequelizeUniqueConstraintError") {
      return "Contact with this email already exists";
    }

    return null;
  }

  constructor(mapper: IContactMapper) {
    super();
    this._mapper = mapper;
  }

  async findAll(transaction?: Transaction): Promise<Result<Collection<Contact>, Error>> {
    try {
      const rawContacts: any = await this._findAll(ContactModel, {}, transaction);

      if (!rawContacts === true) {
        return Result.fail(new Error("Contact with email not exists"));
      }

      return this._mapper.mapArrayToDomain(rawContacts);
    } catch (error: any) {
      return this._handleDatabaseError(error, this._customErrorMapper);
    }
  }

  async findById(id: UniqueID, transaction?: Transaction): Promise<Result<Contact, Error>> {
    try {
      const rawContact: any = await this._getById(ContactModel, id, {}, transaction);

      if (!rawContact === true) {
        return Result.fail(new Error(`Contact with id ${id.toString()} not exists`));
      }

      return this._mapper.mapToDomain(rawContact);
    } catch (error: any) {
      return this._handleDatabaseError(error, this._customErrorMapper);
    }
  }

  async findByEmail(
    email: EmailAddress,
    transaction?: Transaction
  ): Promise<Result<Contact, Error>> {
    try {
      const rawContact: any = await this._getBy(
        ContactModel,
        "email",
        email.toString(),
        {},
        transaction
      );

      if (!rawContact === true) {
        return Result.fail(new Error(`Contact with email ${email.toString()} not exists`));
      }

      return this._mapper.mapToDomain(rawContact);
    } catch (error: any) {
      return this._handleDatabaseError(error, this._customErrorMapper);
    }
  }
}

const contactRepository = new ContactRepository(contactMapper);
export { contactRepository };
