import type { LoginResult } from '@core/identity/application/use-cases/LoginUseCase';
import type { SignupSponsorResult } from '@core/identity/application/use-cases/SignupSponsorUseCase';
import type { SignupResult } from '@core/identity/application/use-cases/SignupUseCase';
import type { UseCaseOutputPort } from '@core/shared/application/UseCaseOutputPort';
import { AuthenticatedUserDTO } from '../dtos/AuthDto';

type AuthSessionResult = LoginResult | SignupResult | SignupSponsorResult;

export class AuthSessionPresenter implements UseCaseOutputPort<AuthSessionResult> {
  private model: AuthenticatedUserDTO | null = null;

  reset(): void {
    this.model = null;
  }

  present(result: AuthSessionResult): void {
    const primaryDriverId = result.user.getPrimaryDriverId();
    const avatarUrl = result.user.getAvatarUrl();
    const companyId = result.user.getCompanyId();
    this.model = {
      userId: result.user.getId().value,
      email: result.user.getEmail() ?? '',
      displayName: result.user.getDisplayName() ?? '',
      ...(primaryDriverId !== undefined ? { primaryDriverId } : {}),
      ...(avatarUrl !== undefined ? { avatarUrl } : {}),
      ...(companyId !== undefined ? { companyId } : {}),
    };
  }

  getResponseModel(): AuthenticatedUserDTO {
    if (!this.model) {
      throw new Error('Presenter not presented');
    }
    return this.model;
  }

  get responseModel(): AuthenticatedUserDTO {
    if (!this.model) {
      throw new Error('Presenter not presented');
    }
    return this.model;
  }
}
