import { Injectable } from '@angular/core';
import { Router } from '@angular/router';
import { HttpClient } from '@angular/common/http';
import { BehaviorSubject, Observable, switchMap } from 'rxjs';
import { map } from 'rxjs/operators';

import { AuthService, UserJsonld, UserService } from "@app/core/api/v1";

@Injectable({ providedIn: 'root' })
export class AccountService {
    private userSubject: BehaviorSubject<UserJsonld | null>;
    public user: Observable<UserJsonld | null>;

    constructor(
        private router: Router,
        private http: HttpClient,
        private authService: AuthService,
        private userService: UserService,
    ) {
        let userData = null;
        const storedUser = localStorage.getItem('user');
        if (storedUser) {
            try {
                userData = JSON.parse(storedUser);
            } catch (error) {
                localStorage.removeItem('user');
            }
        }
        this.userSubject = new BehaviorSubject(userData);
        this.user = this.userSubject.asObservable();
    }

    public get userValue() {
        return this.userSubject.value;
    }

    login(email: string, password: string) {
        return this.authService.postCredentialsItem({ email, password })
            .pipe(
                switchMap(response => {
                    localStorage.setItem('token', response.token!);
                    this.userService.configuration.credentials = { 'JWT': () => response.token };
                    return this.userService.usersIdGet(response.dbId!.toString()).pipe(
                        map(user => {
                            const userWithToken = { ...user, token: response.token };
                            localStorage.setItem('user', JSON.stringify(userWithToken));
                            this.userSubject.next(userWithToken);
                            return userWithToken;
                        })
                    );
                })
            );
    }

    logout() {
        localStorage.removeItem('user');
        localStorage.removeItem('token');
        this.userSubject.next(null);
        this.router.navigate(['/account/login']);
    }

    isLoggedIn() {
        return this.userValue !== null;
    }

    isUserAdmin(): boolean {
        return this.userValue?.roles?.includes('ROLE_ADMIN') ?? false;
    }

    userHasRole(role: string): boolean {
        return this.userValue?.roles?.includes(role) ?? false;
    }
}