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 { IFeedRepository } from '../../domain/repositories/IFeedRepository';
import type { FeedItem } from '../../domain/types/FeedItem';

export interface GetUserFeedParams {
  driverId: string;
  limit?: number;
}

export type GetUserFeedInput = GetUserFeedParams;

export interface GetUserFeedResult {
  items: FeedItem[];
}

export type GetUserFeedErrorCode = 'REPOSITORY_ERROR';

export type GetUserFeedApplicationError = ApplicationErrorCode<
  GetUserFeedErrorCode,
  { message: string }
>;

export class GetUserFeedUseCase {
  constructor(
    private readonly feedRepository: IFeedRepository,
    private readonly logger: Logger,
    private readonly output: UseCaseOutputPort<GetUserFeedResult>,
  ) {}

  async execute(
    input: GetUserFeedInput,
  ): Promise<Result<void, GetUserFeedApplicationError>> {
    const { driverId, limit } = input;
    this.logger.debug('GetUserFeedUseCase.execute started', { driverId, limit });

    try {
      const items = await this.feedRepository.getFeedForDriver(driverId, limit);

      this.logger.info('GetUserFeedUseCase.execute succeeded', {
        driverId,
        itemCount: items.length,
      });

      if (items.length === 0) {
        this.logger.warn(`No feed items found for driverId: ${driverId}`);
      }

      const result: GetUserFeedResult = {
        items,
      };

      this.output.present(result);

      return Result.ok(undefined);
    } catch (error) {
      const err = error instanceof Error ? error : new Error(String(error));

      this.logger.error(
        'GetUserFeedUseCase.execute failed',
        err,
        { input },
      );

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