import { ToastrService } from 'ngx-toastr';
import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
import { map, catchError } from 'rxjs/operators';
import { environment } from '../../environments/environment';

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


  private baseUrl = environment.apiBaseUrl;
  private mode = environment.production;


  constructor(
    private http: HttpClient,
    private toastr: ToastrService
  ) {}

  // Default header
  private getHttpOptions() {
    const token = localStorage.getItem('access_token');
    const headers = new HttpHeaders({
      'Content-Type': 'application/json',
      ...(token ? { 'Authorization': `Bearer ${token}` } : {})
    });
    return { headers };
  }

  // Log ต้นแบบ
  // private logRequest(method: string, url: string, body?: any) {
  //   if (this.mode === 'development') {
  //     console.log(`📡 [${method}] ${url}`, body || '');
  //   }
  // }


  // 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);
    const fullUrl = `${this.baseUrl}${uri}`;
    return this.http.post(fullUrl, payload, this.getHttpOptions()).pipe(
      map((res: any) => res),
      catchError((error: any) => {
        const response = error?.error;
        console.error('❌ [POST Request Error]:', error);
          return throwError(() => ({
          status: error.status,
          code: response?.code ?? '500',
          message: response?.message ?? 'Internal Server Error',
          message_th: response?.message_th ?? 'เกิดข้อผิดพลาดภายในเซิร์ฟเวอร์'
        }));
      })
    );
  }

  // GET Request
  getRequest(uri: string): Observable<any> {
    const fullUrl = `${this.baseUrl}${uri}`;
    return this.http.get(fullUrl, this.getHttpOptions()).pipe(
      map((res: any) => res),
      catchError((error: any) => {
        const response = error?.error;
        console.error('❌ [GET Request Error]:', error);
        return throwError(() => ({
          status: error.status,
          code: response?.code ?? '500',
          message: response?.message ?? 'Internal Server Error',
          message_th: response?.message_th ?? 'เกิดข้อผิดพลาดภายในเซิร์ฟเวอร์'
        }));      })
    );
  }

  // PUT Request
  putRequest(uri: string, body: any): Observable<any> {
    const payload = this.wrapRequestBody(body);
    const fullUrl = `${this.baseUrl}${uri}`;
    return this.http.put(fullUrl, 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);
    const fullUrl = `${this.baseUrl}${uri}`;
    return this.http.delete(fullUrl, { ...this.getHttpOptions(), body: payload }).pipe(
      map((res: any) => res),
      catchError((error: any) => {
        console.error('❌ [DELETE Request Error]:', error);
        return throwError(() => error);
      })
    );
  }

  // showToast(type: 'success' | 'error' | 'warning' | 'info', message: string, title?: string) {
  //   const options = {
  //     positionClass: 'toast-top-right',
  //     timeOut: 3000,
  //     progressBar: true,
  //     progressAnimation: 'decreasing',
  //     toastClass: 'ngx-toastr bg-white bg-opacity-90 shadow-lg border'
  //   };
  //   this.toastr[type](message, title || type.toUpperCase(), options);
  // }


 trowApi(result: any){
  const code = result?.code ?? 500;
  const msg = result?.message ?? 'unknow';
  const msgTh = result?.message_th ?? 'unknow';

  if(code == 200){
    this.toastr.success(`${msgTh || msg}`,'success',{
    positionClass: 'toast-top-right',
    timeOut: 2500,
    progressBar: true,
    progressAnimation: 'decreasing',
    toastClass:
    'ngx-toastr success-toast bg-white bg-opacity-90 text-green-700 shadow-lg'
  });
  } else {
    this.toastr.error(`${msgTh || msg}`,'error',{
    positionClass: 'toast-top-right',
    timeOut: 3500,
    progressBar: true,
    progressAnimation: 'decreasing',
    toastClass:
    'ngx-toastr error-toast bg-white bg-opacity-90 text-red-700 shadow-lg'
  });
  }
 }
}
