/**
 * @copyright 2026 NHCarrigan
 * @license Naomi's Public License
 * @author Naomi Carrigan
 */

import { Injectable, signal, inject } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Observable, switchMap, tap, of } from 'rxjs';
import { environment } from '../../environments/environment';

interface CsrfTokenResponse {
  csrfToken: string;
}

@Injectable({
  providedIn: 'root'
})
export class ApiService {
  private http = inject(HttpClient);
  private readonly apiUrl = environment.apiUrl;
  private csrfToken = signal<string | null>(null);

  private getHeaders(): HttpHeaders {
    const headers: Record<string, string> = {
      'Content-Type': 'application/json'
    };

    const token = this.csrfToken();
    if (token) {
      headers['X-CSRF-Token'] = token;
    }

    return new HttpHeaders(headers);
  }

  private ensureCsrfToken(): Observable<string> {
    const existingToken = this.csrfToken();
    if (existingToken) {
      return of(existingToken);
    }

    return this.http.get<CsrfTokenResponse>(`${this.apiUrl}/auth/csrf-token`, {
      withCredentials: true
    }).pipe(
      tap(response => this.csrfToken.set(response.csrfToken)),
      switchMap(response => of(response.csrfToken))
    );
  }

  get<T>(endpoint: string): Observable<T> {
    return this.http.get<T>(`${this.apiUrl}${endpoint}`, {
      headers: this.getHeaders(),
      withCredentials: true
    });
  }

  post<T>(endpoint: string, body: unknown): Observable<T> {
    return this.ensureCsrfToken().pipe(
      switchMap(() => this.http.post<T>(`${this.apiUrl}${endpoint}`, body, {
        headers: this.getHeaders(),
        withCredentials: true
      }))
    );
  }

  put<T>(endpoint: string, body: unknown): Observable<T> {
    return this.ensureCsrfToken().pipe(
      switchMap(() => this.http.put<T>(`${this.apiUrl}${endpoint}`, body, {
        headers: this.getHeaders(),
        withCredentials: true
      }))
    );
  }

  delete<T>(endpoint: string): Observable<T> {
    return this.ensureCsrfToken().pipe(
      switchMap(() => {
        // Don't send Content-Type for DELETE requests as they have no body
        const headers: Record<string, string> = {};
        const token = this.csrfToken();
        if (token) {
          headers['X-CSRF-Token'] = token;
        }
        return this.http.delete<T>(`${this.apiUrl}${endpoint}`, {
          headers: new HttpHeaders(headers),
          withCredentials: true
        });
      })
    );
  }

  clearCsrfToken(): void {
    this.csrfToken.set(null);
  }
}
