// src/app/products/product.service.ts
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
import { tap, catchError } from 'rxjs/operators';
import { environment } from '@environments/environment';

export interface Product {
  id?: number;
  product_id?: string;
  product_name: string;
  price: number;
  product_image?: string | null;
  created_date: Date | string;
  category?: string;
  selected?: boolean; // For UI selection state
  
  // NEW: Billing and expiration dates
  billing_date?: Date | string | null;
  expiration_date?: Date | string | null;
  
  // Created by fields (automatic from backend)
  created_by?: number;
  created_by_username?: string;
}

@Injectable({
  providedIn: 'root'
})
export class ProductService {
  private apiUrl = environment.apiUrl2; // '/products' endpoint

  constructor(private http: HttpClient) {}

  getProducts(): Observable<Product[]> {
    return this.http.get<Product[]>(this.apiUrl).pipe(
      tap((products) => console.log('Fetched products:', products)),
      catchError((error) => {
        console.error('Error fetching products:', error);
        throw error;
      })
    );
  }

  addProduct(product: FormData): Observable<Product> {
    // Backend automatically extracts created_by from JWT token
    return this.http.post<Product>(this.apiUrl, product).pipe(
      tap((newProduct) => console.log('Added product:', newProduct)),
      catchError((error) => {
        console.error('Error adding product:', error);
        throw error;
      })
    );
  }

  updateProduct(id: number, product: FormData): Observable<Product> {
    return this.http.put<Product>(`${this.apiUrl}/${id}`, product).pipe(
      tap((updated) => console.log('Updated product:', updated)),
      catchError((error) => {
        console.error('Error updating product:', error);
        throw error;
      })
    );
  }

  deleteProduct(id: number): Observable<void> {
    return this.http.delete<void>(`${this.apiUrl}/${id}`).pipe(
      tap(() => console.log('Deleted product:', id)),
      catchError((error) => {
        console.error('Error deleting product:', error);
        throw error;
      })
    );
  }

  /**
   * Helper method to get full image URL
   */
  getImageUrl(imagePath: string | null | undefined): string {
    if (!imagePath) {
      return 'assets/images/product-placeholder.png';
    }
    
    // Remove leading slash if present
    const cleanPath = imagePath.startsWith('/') ? imagePath.substring(1) : imagePath;
    
    return `${environment.apiUrl}/${cleanPath}`;
  }
}