import type { Logger, UseCaseOutputPort, UseCase } from '@core/shared/application'; import type { IPageViewRepository } from '../../domain/repositories/IPageViewRepository'; import { PageView } from '../../domain/entities/PageView'; import type { EntityType, VisitorType } from '../../domain/types/PageView'; import { Result } from '@core/shared/application/Result'; import type { ApplicationErrorCode } from '@core/shared/errors/ApplicationErrorCode'; export interface RecordPageViewInput { entityType: EntityType; entityId: string; visitorId?: string; visitorType: VisitorType; sessionId: string; referrer?: string; userAgent?: string; country?: string; } export interface RecordPageViewOutput { pageViewId: string; } export type RecordPageViewErrorCode = 'REPOSITORY_ERROR'; export class RecordPageViewUseCase implements UseCase { constructor( private readonly pageViewRepository: IPageViewRepository, private readonly logger: Logger, private readonly output: UseCaseOutputPort, ) {} async execute(input: RecordPageViewInput): Promise>> { try { const props = { id: crypto.randomUUID(), entityType: input.entityType, entityId: input.entityId, visitorType: input.visitorType, sessionId: input.sessionId, } as any; if (input.visitorId !== undefined) { props.visitorId = input.visitorId; } if (input.referrer !== undefined) { props.referrer = input.referrer; } if (input.userAgent !== undefined) { props.userAgent = input.userAgent; } if (input.country !== undefined) { props.country = input.country; } const pageView = PageView.create(props); await this.pageViewRepository.save(pageView); const resultModel: RecordPageViewOutput = { pageViewId: pageView.id, }; this.output.present(resultModel); this.logger.info('Page view recorded', { pageViewId: pageView.id, entityId: input.entityId, entityType: input.entityType, }); return Result.ok(undefined); } catch (error) { const err = error as Error; this.logger.error('Failed to record page view', err, { input }); return Result.err({ code: 'REPOSITORY_ERROR', details: { message: err.message ?? 'Failed to record page view' }, }); } } }