import axios from 'axios';

const API_URL = 'http://localhost:8000'; // Adjust if backend runs elsewhere

export const api = axios.create({
    baseURL: API_URL,
    headers: {
        'Content-Type': 'application/json',
    },
});

export const login = async (url, consumer_key, consumer_secret) => {
    const response = await api.post('/login', { url, consumer_key, consumer_secret });
    // Store creds in localStorage for convenience in this demo app
    localStorage.setItem('wc_creds', JSON.stringify({ url, consumer_key, consumer_secret }));
    return response.data;
};

export const getStoredCreds = () => {
    const stored = localStorage.getItem('wc_creds');
    return stored ? JSON.parse(stored) : null;
};

export const logout = () => {
    localStorage.removeItem('wc_creds');
};

export const getProducts = async (page = 1, search = '') => {
    const creds = getStoredCreds();
    if (!creds) throw new Error('Not logged in');

    const response = await api.get('/products', {
        params: {
            ...creds,
            page,
            search
        }
    });
    return response.data;
};

export const getProduct = async (id) => {
    const creds = getStoredCreds();
    if (!creds) throw new Error('Not logged in');

    const response = await api.get(`/products/${id}`, {
        params: { ...creds }
    });
    return response.data;
};

export const createProduct = async (productData) => {
    const creds = getStoredCreds();
    if (!creds) throw new Error('Not logged in');

    const response = await api.post('/products', productData, {
        params: { ...creds }
    });
    return response.data;
};

export const updateProduct = async (id, productData) => {
    const creds = getStoredCreds();
    if (!creds) throw new Error('Not logged in');

    const response = await api.put(`/products/${id}`, productData, {
        params: { ...creds }
    });
    return response.data;
};

export const deleteProduct = async (id) => {
    const creds = getStoredCreds();
    if (!creds) throw new Error('Not logged in');

    const response = await api.delete(`/products/${id}`, {
        params: { ...creds }
    });
    return response.data;
};

export const uploadImage = async (file) => {
    const creds = getStoredCreds();
    if (!creds) throw new Error('Not logged in');

    const formData = new FormData();
    formData.append('file', file);

    // Pass creds as query params because we are sending form data body
    const response = await api.post('/upload', formData, {
        params: { ...creds },
        headers: {
            'Content-Type': 'multipart/form-data'
        }
    });
    return response.data;
}
