import { EntityNotFoundError, SequelizeRepository, translateSequelizeError } from "@erp/core/api";

import { UniqueID } from "@repo/rdx-ddd";
import { Result } from "@repo/rdx-utils";
import { Transaction } from "sequelize";
import { DocNumber, IDocNumberingRepository } from "../../../domain";
import { DocNumberModel } from "../models";

export class DocNumberRepository
  extends SequelizeRepository<DocNumber>
  implements IDocNumberingRepository
{
  async getByReferenceInCompany(
    companyId: UniqueID,
    reference: string,
    transaction?: unknown
  ): Promise<Result<DocNumber, Error>> {
    try {
      const mapper: IDocNumberDomainMapper = this._registry.getDomainMapper({
        resource: "doc-number",
      });

      const row = await DocNumberModel.findOne({
        where: { reference, company_id: companyId.toString() },
        transaction,
      });

      if (!row) {
        return Result.fail(new EntityNotFoundError("Customer", "id", id.toString()));
      }

      const customer = mapper.mapToDomain(row);
      return customer;
    } catch (error: any) {
      return Result.fail(translateSequelizeError(error));
    }
  }
  save(reference: string, transaction?: Transaction): Promise<Result<DocNumber, Error>> {
    throw new Error("Method not implemented.");
  }
}
