// src/services/productService.jsx
import axios from 'axios';
import API_BASE_URL from '../config/api';

class ProductService {
  constructor() {
    this.token = null; // in-memory token

    this.api = axios.create({
      baseURL: API_BASE_URL,
      headers: {
        'Content-Type': 'application/json',
      },
      // withCredentials: true // keep commented unless you use cookie auth
    });

    // Interceptor uses this.token (in-memory)
    this.api.interceptors.request.use((config) => {
      const t = this.token;
      if (t) {
        // ensure token is clean string
        const token = String(t).replace(/(^"|"$)/g, '').trim().replace(/[\r\n\t]+/g, '');
        config.headers = { ...config.headers, Authorization: `Bearer ${token}` };
      }
      return config;
    }, (err) => Promise.reject(err));
  }

  // call this after login or when token becomes available
  setToken(token) {
    this.token = token;
  }

  // optional: allow clearing token (logout)
  clearToken() {
    this.token = null;
  }

  async getProducts(params = {}) {
    const response = await this.api.get('/products', { params });
    return response.data;
  }

  async getProduct(id) {
    const response = await this.api.get(`/products/${id}`);
    return response.data;
  }

  async getCategories() {
    const response = await this.api.get('/products/categories/all');
    return response.data;
  }

  // Note: backend column names use snake_case (see DB). Map fields accordingly.
  async addProduct(productData) {
    // map camelCase keys to DB expected snake_case if needed
    const payload = this._mapClientToServer(productData);
    const response = await this.api.post('/products', payload);
    return response.data;
  }

  async updateProduct(id, productData) {
    const payload = this._mapClientToServer(productData);
    const response = await this.api.put(`/products/${id}`, payload);
    return response.data;
  }

  async deleteProduct(id) {
    const response = await this.api.delete(`/products/${id}`);
    return response.data;
  }

  // helper to map client camelCase -> server snake_case (adjust as necessary)
  _mapClientToServer(data = {}) {
    const mapped = {};
    if (data.name !== undefined) mapped.name = data.name;
    if (data.description !== undefined) mapped.description = data.description;
    if (data.price !== undefined) mapped.price = data.price;
    if (data.imageUrl !== undefined) mapped.image_url = data.imageUrl;
    if (data.imageUrl1 !== undefined) mapped.image_url1 = data.imageUrl1;
    if (data.stockQuantity !== undefined) mapped.stock_quantity = data.stockQuantity;
    if (data.category !== undefined) mapped.category = data.category;
    if (data.details !== undefined) mapped.details = data.details;
    if (data.sizeAvailable !== undefined) mapped.size_available = data.sizeAvailable;
    return mapped;
  }
}

export default new ProductService();