import type { IdentityProviderPort, AuthProvider, StartAuthCommand } from '../ports/IdentityProviderPort';
import { Result } from '@core/shared/application/Result';
import type { ApplicationErrorCode } from '@core/shared/errors/ApplicationErrorCode';
import type { UseCaseOutputPort, Logger } from '@core/shared/application';

export type StartAuthInput = {
  provider: AuthProvider;
  returnTo?: StartAuthCommand['returnTo'];
};

export type StartAuthResult = {
  redirectUrl: string;
  state: string;
};

export type StartAuthErrorCode = 'REPOSITORY_ERROR';

export type StartAuthApplicationError = ApplicationErrorCode<StartAuthErrorCode, { message: string }>;

export class StartAuthUseCase {
  constructor(
    private readonly provider: IdentityProviderPort,
    private readonly logger: Logger,
    private readonly output: UseCaseOutputPort<StartAuthResult>,
  ) {}

  async execute(input: StartAuthInput): Promise<Result<void, StartAuthApplicationError>> {
    try {
      const command: StartAuthCommand = input.returnTo
        ? {
            provider: input.provider,
            returnTo: input.returnTo,
          }
        : {
            provider: input.provider,
          };

      const { redirectUrl, state } = await this.provider.startAuth(command);

      const result: StartAuthResult = { redirectUrl, state };
      this.output.present(result);

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

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

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