/**
 * Application Use Case: GetAllNotificationsUseCase
 *
 * Retrieves all notifications for a recipient.
 */

import type { Logger } from '@core/shared/domain/Logger';
import { Result } from '@core/shared/domain/Result';
import type { ApplicationErrorCode } from '@core/shared/errors/ApplicationErrorCode';
import type { Notification } from '../../domain/entities/Notification';
import type { NotificationRepository } from '../../domain/repositories/NotificationRepository';

export type GetAllNotificationsInput = {
  recipientId: string;
};

export interface GetAllNotificationsResult {
  notifications: Notification[];
  totalCount: number;
}

export type GetAllNotificationsErrorCode = 'REPOSITORY_ERROR';

export class GetAllNotificationsUseCase {
  constructor(
    private readonly notificationRepository: NotificationRepository,
    private readonly logger: Logger,
  ) {}

  async execute(
    input: GetAllNotificationsInput,
  ): Promise<Result<GetAllNotificationsResult, ApplicationErrorCode<GetAllNotificationsErrorCode, { message: string }>>> {
    const { recipientId } = input;
    this.logger.debug(
      `Attempting to retrieve all notifications for recipient ID: ${recipientId}`,
    );

    try {
      const notifications = await this.notificationRepository.findByRecipientId(
        recipientId,
      );
      this.logger.info(
        `Successfully retrieved ${notifications.length} notifications for recipient ID: ${recipientId}`,
      );

      return Result.ok<GetAllNotificationsResult, ApplicationErrorCode<GetAllNotificationsErrorCode, { message: string }>>({
        notifications,
        totalCount: notifications.length,
      });
    } catch (error) {
      const err = error instanceof Error ? error : new Error(String(error));
      this.logger.error(
        `Failed to retrieve notifications for recipient ID: ${recipientId}`,
        err,
      );

      return Result.err<GetAllNotificationsResult, ApplicationErrorCode<GetAllNotificationsErrorCode, { message: string }>>({
        code: 'REPOSITORY_ERROR',
        details: { message: err.message },
      });
    }
  }
}
