import { Injectable } from '@angular/core';
import { HttpClient } from "@angular/common/http";
import {environment} from "../../environments/environment";
import {UserService} from "./user.service";

@Injectable({
  providedIn: 'root'
})
export class FollowService {

  userFollowStatus: Map<number, boolean> = new Map<number, boolean>();

  constructor(
    private userService: UserService,
    private httpClient: HttpClient
  ) { }

  removeUserFollow(userId: number): Promise<boolean> {
    if(!this.userService.isUserLoggedIn()) {
      return Promise.resolve(false);
    }

    const body = {
      userIds: [userId]
    }
    return new Promise((resolve, reject) => {
      this.httpClient.delete(`${environment.apiUrl}/follows`, { body: body })
        .subscribe({
          next: () => {
            this.userFollowStatus.set(userId, false);
            resolve(true);
          },
          error: (err) => {
            reject(err);
          }
        });
    });
  }

  addNewUserFollow(userId: number): Promise<boolean> {
    if(!this.userService.isUserLoggedIn()) {
      return Promise.resolve(false);
    }

    const body = {
      userIds: [userId]
    }
    return new Promise((resolve, reject) => {
      this.httpClient.put(`${environment.apiUrl}/follows`, body)
        .subscribe({
          next: () => {
            this.userFollowStatus.set(userId, true);
            resolve(true);
          },
          error: (err) => {
            reject(err);
          }
        });
    });
  }

  checkIfUserIsFollowed(userId: number): Promise<boolean> {
    if(!this.userService.isUserLoggedIn()) {
      return Promise.resolve(false);
    }

    return new Promise<boolean>((resolve, reject) => {
      this.httpClient.get<boolean>(`${environment.apiUrl}/follows/${userId}`)
        .subscribe({
          next: (isFollowing) => {
            this.userFollowStatus.set(userId, isFollowing);
            resolve(isFollowing);
          },
          error: (err) => {
            if (err.status === 404) {
              this.userFollowStatus.set(userId, false);
              resolve(false);
            } else {
              reject(err);
            }
          }
        });
    });
  }

}
