/**
 * Application Use Case: GetUnreadNotificationsUseCase
 *
 * Retrieves unread notifications for a recipient.
 */

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

export type GetUnreadNotificationsInput = {
  recipientId: string;
};

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

export type GetUnreadNotificationsErrorCode = 'REPOSITORY_ERROR';

export class GetUnreadNotificationsUseCase {
  constructor(
    private readonly notificationRepository: INotificationRepository,
    private readonly output: UseCaseOutputPort<GetUnreadNotificationsResult>,
    private readonly logger: Logger,
  ) {}

  async execute(
    input: GetUnreadNotificationsInput,
  ): Promise<Result<void, 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}`);
      }

      this.output.present({
        notifications,
        totalCount: notifications.length,
      });

      return Result.ok<void, ApplicationErrorCode<GetUnreadNotificationsErrorCode, { message: string }>>(
        undefined,
      );
    } 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<void, 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.
 */