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 { AuthProvider, IdentityProviderPort, StartAuthCommand } from '../ports/IdentityProviderPort';

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,
  ) {}

  async execute(input: StartAuthInput): Promise<Result<StartAuthResult, 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 };

      return Result.ok(result);
    } 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);
    }
  }
}