import { apiClient } from './api/client';

export interface Product {
    id: string;
    title: string;
    description: string;
    price: number;
    currency: string;
    category: string;
    tags: string[];
    cover_url?: string;
    preview_url?: string;
    file_url?: string;
    status: 'draft' | 'active' | 'archived';
    owner_id: string;
    license_type: 'personal' | 'commercial' | 'exclusive';
    metadata: {
        bpm?: string;
        key?: string;
        format?: string;
    };
    created_at: string;
    updated_at: string;
}

export interface CreateProductData {
    title: string;
    description: string;
    price: number;
    category: string;
    tags: string[];
    license_type: 'personal' | 'commercial' | 'exclusive';
    bpm?: string;
    key?: string;
}

export const productService = {
    list: async (params?: { page?: number; limit?: number; category?: string }) => {
        const response = await apiClient.get<{ products: Product[]; total: number }>(
            '/marketplace/products',
            { params }
        );
        return response.data;
    },

    get: async (id: string) => {
        const response = await apiClient.get<{ product: Product }>(`/marketplace/products/${id}`);
        return response.data.product;
    },

    create: async (data: CreateProductData) => {
        const response = await apiClient.post<{ product: Product }>(
            '/marketplace/products',
            data
        );
        return response.data.product;
    },

    update: async (id: string, data: Partial<CreateProductData>) => {
        const response = await apiClient.put<{ product: Product }>(
            `/marketplace/products/${id}`,
            data
        );
        return response.data.product;
    },

    delete: async (id: string) => {
        await apiClient.delete(`/marketplace/products/${id}`);
    },

    uploadFile: async (id: string, file: File, type: 'main' | 'preview' | 'cover') => {
        const formData = new FormData();
        formData.append('file', file);
        formData.append('type', type);

        const response = await apiClient.post<{ url: string }>(
            `/marketplace/products/${id}/upload`,
            formData,
            {
                headers: {
                    'Content-Type': 'multipart/form-data',
                },
            }
        );
        return response.data;
    }
};
