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

export interface Category {
  id: number;
  category_id: string;
  name: string;
  image: string | null;
  brand_id: string;
  brand_name: string;
  branch_id: string;
  branch_name: string;
  created_at: string;
  updated_at: string;
  
  // ⭐ NEW: Created by fields (automatic from backend)
  created_by?: number;
  created_by_username?: string;
}

@Injectable({
  providedIn: 'root'
})
export class CategoryService {
  private apiUrl = `${environment.apiUrl}/categories`;

  constructor(private http: HttpClient) {}

  private getHeaders(): HttpHeaders {
    const token = localStorage.getItem('accessToken');
    return new HttpHeaders({
      'Authorization': token ? `Bearer ${token}` : ''
    });
  }

  getAllCategories(): Observable<Category[]> {
    return this.http.get<Category[]>(this.apiUrl, { headers: this.getHeaders() })
      .pipe(catchError(this.handleError));
  }

  getCategory(id: number): Observable<Category> {
    return this.http.get<Category>(`${this.apiUrl}/${id}`, { headers: this.getHeaders() })
      .pipe(catchError(this.handleError));
  }

  /**
   * Create new category (with FormData for image upload)
   * ⭐ NOTE: Don't add created_by to FormData
   * Backend automatically extracts it from JWT token
   */
  createCategory(formData: FormData): Observable<Category> {
    const token = localStorage.getItem('accessToken');
    const headers = new HttpHeaders({
      'Authorization': token ? `Bearer ${token}` : ''
    });
    return this.http.post<Category>(this.apiUrl, formData, { headers })
      .pipe(catchError(this.handleError));
  }

  /**
   * Update existing category (with FormData for image upload)
   * ⭐ NOTE: Don't update created_by
   * It's set once during creation and shouldn't change
   */
  updateCategory(id: number, formData: FormData): Observable<Category> {
    const token = localStorage.getItem('accessToken');
    const headers = new HttpHeaders({
      'Authorization': token ? `Bearer ${token}` : ''
    });
    return this.http.put<Category>(`${this.apiUrl}/${id}`, formData, { headers })
      .pipe(catchError(this.handleError));
  }

  deleteCategory(id: number): Observable<{ message: string }> {
    return this.http.delete<{ message: string }>(`${this.apiUrl}/${id}`, { headers: this.getHeaders() })
      .pipe(catchError(this.handleError));
  }

  searchCategories(query: string): Observable<Category[]> {
    return this.http.get<Category[]>(`${this.apiUrl}/search?q=${encodeURIComponent(query)}`, 
      { headers: this.getHeaders() })
      .pipe(catchError(this.handleError));
  }

  getCategoriesByBrand(brandId: string): Observable<Category[]> {
    return this.http.get<Category[]>(`${this.apiUrl}/by-brand/${brandId}`, 
      { headers: this.getHeaders() })
      .pipe(catchError(this.handleError));
  }

  getCategoriesByBranch(branchId: string): Observable<Category[]> {
    return this.http.get<Category[]>(`${this.apiUrl}/by-branch/${branchId}`, 
      { headers: this.getHeaders() })
      .pipe(catchError(this.handleError));
  }

  private handleError(error: any): Observable<never> {
    console.error('API Error:', error);
    let errorMessage = 'An error occurred';
    if (error.error instanceof ErrorEvent) {
      errorMessage = error.error.message;
    } else {
      errorMessage = error.error?.error || error.message || 'Server error';
    }
    return throwError(() => ({ error: errorMessage, status: error.status }));
  }
}