import api from './api';

const authService = {
    /**
     * Login user
     */
    login: async (username, password) => {
        const response = await api.post('/auth/login', { username, password });
        if (response.data.data.token) {
            localStorage.setItem('token', response.data.data.token);
            localStorage.setItem('user', JSON.stringify(response.data.data.user));
        }
        return response.data.data;
    },

    /**
     * Logout user
     */
    logout: async () => {
        try {
            await api.post('/auth/logout');
        } catch (error) {
            // Ignore errors on logout
        } finally {
            localStorage.removeItem('token');
            localStorage.removeItem('user');
        }
    },

    /**
     * Get current user info
     */
    getCurrentUser: async () => {
        const response = await api.get('/auth/me');
        return response.data.data;
    },

    /**
     * Change password
     */
    changePassword: async (currentPassword, newPassword) => {
        const response = await api.post('/auth/change-password', {
            currentPassword,
            newPassword,
        });
        return response.data.data;
    },

    /**
     * Get user from localStorage
     */
    getStoredUser: () => {
        const user = localStorage.getItem('user');
        return user ? JSON.parse(user) : null;
    },

    /**
     * Get token from localStorage
     */
    getToken: () => {
        return localStorage.getItem('token');
    },

    /**
     * Check if user is authenticated
     */
    isAuthenticated: () => {
        return !!localStorage.getItem('token');
    },

    /**
     * Fetch user data using a token (for kiosk URL-token login)
     */
    fetchUserFromToken: async (token) => {
        try {
            const response = await fetch('/api/auth/me', {
                headers: { Authorization: `Bearer ${token}` },
            });
            if (!response.ok) return null;
            const data = await response.json();
            return data.data || data.user || data;
        } catch {
            return null;
        }
    },
};

export default authService;
