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 SubCategory {
  id: number;
  sub_category_id: string;
  name: string;
  image: string | null;
  category_id: string;
  category_name: string;
  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 SubCategoryService {
  private apiUrl = `${environment.apiUrl}/subcategories`;

  constructor(private http: HttpClient) {}

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

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

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

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

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

  deleteSubCategory(id: number): Observable<{ message: string }> {
    return this.http.delete<{ message: string }>(`${this.apiUrl}/${id}`, { 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 }));
  }
}