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

export interface AchievementRepository {
  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: AchievementRepository,
    private readonly logger: Logger,
  ) {}

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

      const result: CreateAchievementResult = { achievement };

      return Result.ok(result);
    } 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);
    }
  }
}