import { HttpClient } from '@angular/common/http';
import {
  computed,
  inject,
  Injectable,
  Signal,
  signal,
  WritableSignal,
} from '@angular/core';
import { Post } from '../interfaces/post';
import { environment } from '../../../environments/environment';

@Injectable({
  providedIn: 'root',
})
export class PostsService {
  private http = inject(HttpClient);
  private posts: WritableSignal<Map<number, Post>> = signal(new Map());

  constructor() {
    this.updatePosts(); // Pull posts immediately when the service is instantiated
  }

  updatePosts() {
    this.http
      .get<Post[]>(`${environment.apiRoot}/posts`)
      .subscribe((res) => this.posts.set(new Map(res.map((p) => [p.id, p]))));
  }
  getPosts(): Signal<Post[]> {
    return computed(() =>
      Array.from(this.posts().values()).sort((a, b) => b.id - a.id),
    );
  }

  getPost(id: number): Signal<Post | undefined> {
    return computed(() => this.posts().get(id));
  }

  deletePost(id: number) {
    this.http.delete(`${environment.apiRoot}/posts/${id}`).subscribe(() => {
      this.posts.update((p) => {
        p.delete(id);
        return new Map(p);
      });
    });
  }

  createPost(post: Post) {
    this.http
      .post<Post>(`${environment.apiRoot}/posts`, post)
      .subscribe((res) => {
        this.posts.update((p) => new Map(p.set(res.id, res)));
      });
  }
  updatePost(post: Post) {
    this.http
      .put<Post>(`${environment.apiRoot}/posts`, post)
      .subscribe((res) => {
        this.posts.update((p) => new Map(p.set(res.id, res)));
      });
  }
}
