import {Injectable} from '@angular/core';
import {HttpClient, HttpHeaders} from '@angular/common/http';
import {Observable} from 'rxjs';
import {Author} from '../models/author';
import {Post} from '../models/post';

@Injectable({
  providedIn: 'root'
})
export class AuthorService {
  url: string = "http://localhost:8080/api/authors";

  constructor(private httpClient: HttpClient) {}

  list(): Observable<Author[]> {
    return this.httpClient.get<Author[]>(this.url);
  }

  login(name: string, password: string) {
    return this.httpClient.post<any>(`${this.url}/login`, {name: name, password: password})
  }

  me(token: string): Observable<Author> {
    const headers = new HttpHeaders().set("Authorization", "Bearer " + token);
    return this.httpClient.get<Author>(`${this.url}/me`, {'headers': headers});
  }

  attributePost(authorId: string | undefined, postId: bigint, token: string) {
    const httpOptions = {
      headers: new HttpHeaders({
        'Authorization': `Bearer ${token}`
      })
    };
    return this.httpClient.put<any>(`${this.url}/${authorId}/posts`, postId, httpOptions);
  }

  getAuthor(id: string | null): Observable<Author> {
    if (id) {
      return this.httpClient.get<Author>(`${this.url}/${id}`);
    } else {
      throw new Error("Not Found");
    }
  }

  getAuthorsPosts(id: string | undefined, token: string): Observable<Post[]> {
    const httpOptions = {
      headers: new HttpHeaders({
        'Authorization': `Bearer ${token}`
      })
    };
    return this.httpClient.get<Post[]>(`${this.url}/${id}/posts`, httpOptions);
  }

  createAccount(username: string, password: string): Observable<Author> {
    return this.httpClient.post<Author>(`${this.url}/register`, {name: username, password: password})
  }

  createAccountAdmin(username: string, password: string, role: string): Observable<Author> {
    return this.httpClient.post<Author>(`${this.url}/register`, {name: username, password: password, role: role})
  }
}
