import { Injectable } from '@angular/core';
import { ActivatedRouteSnapshot, Router, RouterStateSnapshot } from '@angular/router';
import { Observable, of } from 'rxjs';
import { catchError, map } from 'rxjs/operators';
import { InvitationsApiService } from '@fleio-api/client-user/invitations/invitations-api.service';
import { ConfigService } from '@shared/config/config.service';

@Injectable({
  providedIn: 'root'
})
export class InvitationResolver  {
  constructor(
    private invitationsApiService: InvitationsApiService,
    private configService: ConfigService,
    private router: Router,
  ) {
  }

  resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot):
    Observable<any> | Promise<any> | any {
    if (route.params.token) {
      return this.invitationsApiService.acceptInvitation(
        route.params.id, route.params.token
      ).pipe(map(data => {
          data.used_token = route.params.token;
          if (data.invitation_automatically_accepted) {
            return this.router.navigateByUrl(this.configService.getPanelUrl('clients'));
          } else if (data.requires_sign_up === false) {
            this.router.navigateByUrl(
              this.configService.getPanelUrl(`login/${data.invitation_id}/${data.used_token}`)
            );
          } else {
            this.router.navigateByUrl(
              this.configService.getPanelUrl(`signup/${data.email}/${data.invitation_id}/${data.used_token}`)
            );
          }
          return data;
        }), catchError(() => of({token_invalid: true}))
      );
    } else {
      return of({token_missing: true});
    }
  }
}
