import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
import { map, catchError } from 'rxjs/operators';

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

  constructor(private http: HttpClient) {}

  // 🧱 Default header
  private getHttpOptions() {
    const headers = new HttpHeaders({
      'Content-Type': 'application/json'
    });
    return { headers };
  }

  // 🧩 Helper: wrap body ให้มี request ครอบเสมอ
  private wrapRequestBody(body: any): any {
    // ถ้ามี request อยู่แล้ว จะไม่ซ้ำ
    if (body && body.request) {
      return body;
    }
    return { request: body ?? {} };
  }

  // 📦 POST Request
  postRequest(uri: string, body: any): Observable<any> {
    const payload = this.wrapRequestBody(body);
    return this.http.post(uri, payload, this.getHttpOptions()).pipe(
      map((res: any) => res),
      catchError((error: any) => {
        console.error('❌ [POST Request Error]:', error);
        return throwError(() => error);
      })
    );
  }

  // 📦 GET Request
  getRequest(uri: string): Observable<any> {
    return this.http.get(uri, this.getHttpOptions()).pipe(
      map((res: any) => res),
      catchError((error: any) => {
        console.error('❌ [GET Request Error]:', error);
        return throwError(() => error);
      })
    );
  }

  // 📦 PUT Request
  putRequest(uri: string, body: any): Observable<any> {
    const payload = this.wrapRequestBody(body);
    return this.http.put(uri, payload, this.getHttpOptions()).pipe(
      map((res: any) => res),
      catchError((error: any) => {
        console.error('❌ [PUT Request Error]:', error);
        return throwError(() => error);
      })
    );
  }

  // 📦 DELETE Request
  deleteRequest(uri: string, body?: any): Observable<any> {
    const payload = this.wrapRequestBody(body);
    return this.http.delete(uri, { ...this.getHttpOptions(), body: payload }).pipe(
      map((res: any) => res),
      catchError((error: any) => {
        console.error('❌ [DELETE Request Error]:', error);
        return throwError(() => error);
      })
    );
  }
}
