import { Achievement, AchievementProps } from '@core/identity/domain/entities/Achievement';
import { Result } from '@core/shared/application/Result';
import type { ApplicationErrorCode } from '@core/shared/errors/ApplicationErrorCode';
import type { UseCaseOutputPort, Logger } from '@core/shared/application';

export interface IAchievementRepository {
  save(achievement: Achievement): Promise<void>;
  findById(id: string): Promise<Achievement | null>;
}

export type CreateAchievementInput = Omit<AchievementProps, 'createdAt'>;

export type CreateAchievementResult = {
  achievement: Achievement;
};

export type CreateAchievementErrorCode = 'REPOSITORY_ERROR';

export type CreateAchievementApplicationError = ApplicationErrorCode<
  CreateAchievementErrorCode,
  { message: string }
>;

export class CreateAchievementUseCase {
  constructor(
    private readonly achievementRepository: IAchievementRepository,
    private readonly logger: Logger,
    private readonly output: UseCaseOutputPort<CreateAchievementResult>,
  ) {}

  async execute(input: CreateAchievementInput): Promise<
    Result<void, CreateAchievementApplicationError>
  > {
    try {
      const achievement = Achievement.create(input);
      await this.achievementRepository.save(achievement);

      const result: CreateAchievementResult = { achievement };
      this.output.present(result);

      return Result.ok(undefined);
    } catch (error) {
      const message =
        error instanceof Error && error.message
          ? error.message
          : 'Failed to execute CreateAchievementUseCase';

      this.logger.error(
        'CreateAchievementUseCase.execute failed',
        error instanceof Error ? error : undefined,
        { input },
      );

      return Result.err({
        code: 'REPOSITORY_ERROR',
        details: { message },
      } as CreateAchievementApplicationError);
    }
  }
}
