import api from './api';

export interface StockItem {
    id?: string;
    _id?: string;
    organizationId?: string;
    dataSheetId: string | any; // Can be object when populated
    rrNumber: string;
    batchNumber: string;
    color?: string;
    invoiceNumber?: string;
    receivedBy?: string;
    quantity: number;
    unit: string;
    minStock?: number;
    expirationDate?: string;
    entryDate?: string;
    notes?: string;
}

export interface StockMovement {
    id?: string;
    _id?: string;
    stockItemId: string;
    type: 'ENTRY' | 'ADJUSTMENT' | 'CONSUMPTION';
    quantity: number;
    date: string;
    responsible: string;
    reason?: string;
    requester?: string;
    notes?: string;
    movementNumber?: number;
}

export const stockService = {
    getAll: async (dataSheetId?: string) => {
        const response = await api.get('/stock', { params: { dataSheetId } });
        return response.data;
    },

    getById: async (id: string) => {
        const response = await api.get(`/stock/${id}`);
        return response.data;
    },

    getMovements: async (id: string) => {
        const response = await api.get(`/stock/${id}/movements`);
        return response.data;
    },

    getAuditLogs: async (id: string) => {
        const response = await api.get(`/stock/${id}/logs`);
        return response.data;
    },

    create: async (data: Partial<StockItem>) => {
        const response = await api.post('/stock', data);
        return response.data;
    },

    update: async (id: string, data: Partial<StockItem>) => {
        const response = await api.put(`/stock/${id}`, data);
        return response.data;
    },

    adjust: async (id: string, data: { quantityDelta: number; reason: string }) => {
        const response = await api.post(`/stock/${id}/adjust`, data);
        return response.data;
    },

    consume: async (id: string, data: { quantityConsumed: number; requester: string; date?: string }) => {
        const response = await api.post(`/stock/${id}/consume`, data);
        return response.data;
    },

    delete: async (id: string) => {
        await api.delete(`/stock/${id}`);
    },

    updateMovement: async (id: string, data: Partial<StockMovement>) => {
        const response = await api.put(`/stock/movements/${id}`, data);
        return response.data;
    },

    deleteMovement: async (id: string) => {
        await api.delete(`/stock/movements/${id}`);
    }
};
