import type { Logger } from '@core/shared/domain/Logger';
import { Result } from '@core/shared/domain/Result';
import type { ApplicationErrorCode } from '@core/shared/errors/ApplicationErrorCode';
import type { AuthCallbackCommand, AuthenticatedUser, IdentityProviderPort } from '../ports/IdentityProviderPort';
import type { AuthSession, IdentitySessionPort } from '../ports/IdentitySessionPort';

export type HandleAuthCallbackInput = AuthCallbackCommand;

export type HandleAuthCallbackResult = AuthSession;

export type HandleAuthCallbackErrorCode = 'REPOSITORY_ERROR';

export type HandleAuthCallbackApplicationError = ApplicationErrorCode<
  HandleAuthCallbackErrorCode,
  { message: string }
>;

export class HandleAuthCallbackUseCase {
  constructor(
    private readonly provider: IdentityProviderPort,
    private readonly sessionPort: IdentitySessionPort,
    private readonly logger: Logger,
  ) {}

  async execute(input: HandleAuthCallbackInput): Promise<
    Result<HandleAuthCallbackResult, HandleAuthCallbackApplicationError>
  > {
    try {
      const user: AuthenticatedUser = await this.provider.completeAuth(input);
      const session = await this.sessionPort.createSession(user);

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

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

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