import { Injectable } from '@angular/core';
import { forkJoin } from 'rxjs';

import { AuthService } from '../auth/auth.service';
import { ApiFitService } from 'src/app/shared/services/api-fit/api-fit.service';

import {
  UserDispatchers,
  SignupDispatchers,
} from '../../stores/index.dispatchers';
@Injectable({
  providedIn: 'root',
})
export class StoreService {
  constructor(
    private authService: AuthService,
    private apiFitService: ApiFitService,
    private userDispatchers: UserDispatchers,
    private signupDistpachers: SignupDispatchers,
  ) {}

  setStore() {
    return new Promise(
      (
        resolve: (success: boolean) => void,
        reject: (reason?: unknown) => void,
      ) => {
        const token = this.authService.getAuthorizationToken();

        if (!token) reject();

        forkJoin([this.apiFitService.getUserInformations()]).subscribe({
          next: ([userResponse]) => {
            this.userDispatchers.setUser(userResponse.data);
            this.signupDistpachers.clearSignup();

            resolve(true);
          },
          error: reject,
        });
      },
    );
  }
}
