import {inject, Injectable, signal, WritableSignal} from '@angular/core';
import {HttpClient} from '@angular/common/http';
import {User} from '../../models/user.model';
import {Credentials} from '../../models/credentials';
import {map, Observable, tap} from 'rxjs';

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

  private readonly http: HttpClient = inject(HttpClient);
  private readonly BASE_URL = 'http://localhost:8000';

  user = signal<User | null | undefined>(undefined);

  login(credentials: Credentials): Observable<User | null | undefined> {
    return this.http.post<User>(this.BASE_URL + '/sessions/login/', credentials).pipe(
      tap((result: any) => {
        localStorage.setItem('token', result.token);
        const user: User = Object.assign(new User(), result['user']);
        this.user.set(user);
      }),
      map((result: any) => {
        return this.user();
      })
    );
  }

  logout(): Observable<null> {
    return this.http.get(this.BASE_URL + '/sessions/logout/').pipe(
      tap(() => {
        localStorage.removeItem('token');
        this.user.set(null);
      }),
      map(() => null)
    );
  }

  getUsers(): Observable<User | null | undefined> {
    return this.http.get(this.BASE_URL + '/sessions/me/').pipe(
      tap((result: any) => {
        const user: User = Object.assign(new User(), result);
        this.user.set(user);
      }),
      map((result: any) => {
        return this.user();
      })
    );
  }
}
