import { apiClient } from './client';
import { User, Product, ApiResponse, UpdateUserProfileData } from '@/types/user';

export const usersApi = {
    // Get user status by email or mobile - package name is now a parameter
    getUserStatus: async (identifier: string, packageName: string, token: string): Promise<User> => {
        // Check if identifier is email or mobile
        const isEmail = identifier.includes('@');
        const endpoint = isEmail
            ? `/admin/users/${identifier}/status?package_name=${packageName}`
            : `/admin/users/${identifier}/status?package_name=${packageName}`;

        return apiClient.get<User>(endpoint, token);
    },

    // Subscribe user to a product
    subscribeUser: async (identifier: string, productId: number, token: string): Promise<ApiResponse<any>> => {
        const data = {
            product_id: productId
        };

        return apiClient.put<ApiResponse<any>>(
            `/admin/users/${identifier}/status`,
            data,
            token
        );
    },

    // Unsubscribe user from a product
    unsubscribeUser: async (identifier: string, productId: number, token: string): Promise<ApiResponse<any>> => {
        const data = {
            product_id: productId
        };

        return apiClient.delete<ApiResponse<any>>(
            `/admin/users/${identifier}/status`,
            data,
            token
        );
    },

    // Get user transactions
    getUserTransactions: async (userId: number, packageName: string, token: string): Promise<any> => {
        return apiClient.get(`/admin/users/${userId}/transactions?package_name=${packageName}`, token);
    },

    // Get products for a specific package
    getProductsByPackage: async (packageName: string, token: string): Promise<Product[]> => {
        return apiClient.get<Product[]>(`/package-names/${packageName}/products`, token);
    },

    // Update a user's profile (admin). Uses FormData because avatar may be an image file.
    updateUserProfile: async (
        identifier: string,
        data: UpdateUserProfileData,
        token: string
    ): Promise<ApiResponse<any>> => {
        const formData = new FormData();

        Object.entries(data).forEach(([key, value]) => {
            if (value !== null && value !== undefined && value !== '') {
                if (key === 'avatar' && value instanceof File) {
                    formData.append('avatar', value);
                } else if (key !== 'avatar') {
                    formData.append(key, String(value));
                }
            }
        });

        return apiClient.post<ApiResponse<any>>(`/admin/users/${identifier}/profile`, formData, token);
    },

    // Delete a user (admin)
    deleteUser: async (identifier: string, token: string): Promise<ApiResponse<any>> => {
        return apiClient.delete<ApiResponse<any>>(`/admin/users/${identifier}`, undefined, token);
    }
};