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

export interface Branch {
  id: number;
  branch_id: string;
  code: string;
  name: string;
  location: string;
  address: string;
  contact: string;
  created_at: string;
  updated_at: string;
  
  // ⭐ NEW: Created by fields (automatic from backend)
  created_by?: number;
  created_by_username?: string;
}

export interface BranchCreateRequest {
  code: string;
  name: string;
  location: string;
  address: string;
  contact: string;
  // ⭐ NOTE: created_by is NOT included here
  // Backend automatically extracts it from JWT token
}

export interface BranchUpdateRequest extends BranchCreateRequest {}

@Injectable({
  providedIn: 'root'
})
export class BranchService {
  private apiUrl = `${environment.apiUrl}/branches`; // Adjust based on your environment setup

  constructor(private http: HttpClient) {}

  /**
   * Get authorization headers
   */
  private getHeaders(): HttpHeaders {
    const token = localStorage.getItem('accessToken');
    return new HttpHeaders({
      'Content-Type': 'application/json',
      'Authorization': token ? `Bearer ${token}` : ''
    });
  }

  /**
   * Get all branches
   */
  getAllBranches(): Observable<Branch[]> {
    return this.http.get<Branch[]>(this.apiUrl, { headers: this.getHeaders() })
      .pipe(
        catchError(this.handleError)
      );
  }

  /**
   * Get single branch by ID
   */
  getBranch(id: number): Observable<Branch> {
    return this.http.get<Branch>(`${this.apiUrl}/${id}`, { headers: this.getHeaders() })
      .pipe(
        catchError(this.handleError)
      );
  }

  /**
   * Create new branch
   * ⭐ NOTE: Don't send created_by in request
   * Backend automatically extracts it from JWT token
   */
  createBranch(data: BranchCreateRequest): Observable<Branch> {
    return this.http.post<Branch>(this.apiUrl, data, { headers: this.getHeaders() })
      .pipe(
        catchError(this.handleError)
      );
  }

  /**
   * Update existing branch
   * ⭐ NOTE: Don't update created_by
   * It's set once during creation and shouldn't change
   */
  updateBranch(id: number, data: BranchUpdateRequest): Observable<Branch> {
    return this.http.put<Branch>(`${this.apiUrl}/${id}`, data, { headers: this.getHeaders() })
      .pipe(
        catchError(this.handleError)
      );
  }

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

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

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