import { inject } from '@angular/core';
import { ActivatedRouteSnapshot, ResolveFn, Router } from '@angular/router';
import { EMPTY, Observable, of } from 'rxjs';
import { catchError, switchMap, tap } from 'rxjs/operators';
import { AuthService, OAuthLoginData, OAuthService } from '@flaps/core';

export const loginResolver: ResolveFn<OAuthLoginData | null> = (
  route: ActivatedRouteSnapshot,
): Observable<OAuthLoginData | null> => {
  const oAuthService = inject(OAuthService);
  const authService = inject(AuthService);
  const router = inject(Router);
  const loginChallenge = route.queryParamMap.get('login_challenge');
  const userHint = route.queryParamMap.get('user_hint');
  oAuthService.setCameFrom(route.queryParamMap.get('came_from') || '');

  if (!loginChallenge) {
    return of(null);
  }

  return oAuthService.getLoginData(loginChallenge, userHint).pipe(
    tap((data) => {
      if (data.email && data.needs_signup) {
        authService.setSignUpEmail(data.email);
        router.navigate(['/user/signup'], { queryParams: { login_challenge: loginChallenge } });
      } else if (data.skip_login) {
        // Auto-submit the form by creating and submitting it programmatically
        const form = document.createElement('form');
        form.method = 'POST';
        form.action = oAuthService.loginUrl();

        const challengeInput = document.createElement('input');
        challengeInput.type = 'hidden';
        challengeInput.name = 'login_challenge';
        challengeInput.value = loginChallenge;
        form.appendChild(challengeInput);

        document.body.appendChild(form);
        form.submit();
      }
    }),
    switchMap((data) => (data.skip_login ? EMPTY : of(data))),
    catchError(() => of(null)),
  );
};
