import { IPresenterRegistry, ITransactionManager } from "@erp/core/api";
import { Result } from "@repo/rdx-utils";
import { I{{pascalCase name}}Repository } from "../../domain/repositories";
import { {{pascalCase name}} } from "../../domain/aggregates";
import { {{pascalCase name}}FullPresenter } from "../presenters";

type Create{{pascalCase name}}Input = { name: string };

export class Create{{pascalCase name}}UseCase {
  constructor(
    private readonly repo: I{{pascalCase name}}Repository,
    private readonly txManager: ITransactionManager,
    private readonly presenters: IPresenterRegistry
  ) {}

  public execute(params: Create{{pascalCase name}}Input) {
    return this.txManager.complete(async (tx) => {
      const entityOrError = {{pascalCase name}}.create({ name: params.name });
      if (entityOrError.isFailure) return Result.fail(entityOrError.error);

      const savedOrError = await this.repo.save(entityOrError.data, tx);
      if (savedOrError.isFailure) return Result.fail(savedOrError.error);

      const presenter = this.presenters.getPresenter({ resource: "{{kebabCase name}}", projection: "FULL" }) as {{pascalCase name}}FullPresenter;
      return Result.ok(presenter.toOutput(savedOrError.data));
    });
  }
}
