/**
 * Application Use Case: GetUnreadNotificationsUseCase
 *
 * Retrieves unread 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 { NotificationRepository } from '../../domain/repositories/NotificationRepository';

export interface GetUnreadNotificationsInput {
  recipientId: string;
}

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

export type GetUnreadNotificationsErrorCode = 'REPOSITORY_ERROR';

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

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

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

      if (notifications.length === 0) {
        this.logger.warn(`No unread notifications found for recipient ID: ${recipientId}`);
      }

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

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

/**
 * Additional notification query/use case types (e.g., listing or counting notifications)
 * can be added here in the future as needed.
 */
