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

export type GetCurrentSessionInput = {
  userId: string;
};

export type GetCurrentSessionResult = {
  user: User;
};

export type GetCurrentSessionErrorCode = 'USER_NOT_FOUND' | 'REPOSITORY_ERROR';

export type GetCurrentSessionApplicationError = ApplicationErrorCode<
  GetCurrentSessionErrorCode,
  { message: string }
>;

/**
 * Application Use Case: GetCurrentSessionUseCase
 *
 * Retrieves the current user session information.
 */
export class GetCurrentSessionUseCase {
  constructor(
    private readonly userRepo: UserRepository,
    private readonly logger: Logger,
  ) {}

  async execute(input: GetCurrentSessionInput): Promise<
    Result<GetCurrentSessionResult, GetCurrentSessionApplicationError>
  > {
    try {
      const stored = await this.userRepo.findById(input.userId);
      if (!stored) {
        return Result.err({
          code: 'USER_NOT_FOUND',
          details: { message: 'User not found' },
        } as GetCurrentSessionApplicationError);
      }

      const user = User.fromStored(stored);
      const result: GetCurrentSessionResult = { user };

      return Result.ok(result);
    } catch (error) {
      const message =
        error instanceof Error && error.message
          ? error.message
          : 'Failed to execute GetCurrentSessionUseCase';

      this.logger.error(
        'GetCurrentSessionUseCase.execute failed',
        error instanceof Error ? error : undefined,
        { input },
      );

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