import { client } from './client.js'

export async function login(email, password) {
    const response = await client.post('/auth/login', { email, password })

    if (response.data) {
        client.saveTokens(
            response.data.access_token,
            response.data.refresh_token,
            response.data.expires
        )
    }

    return response.data
}

export async function logout() {
    if (client.refreshToken) {
        try {
            await client.post('/auth/logout', { refresh_token: client.refreshToken })
        } catch (e) {
            // Tokens will be cleared anyway
        }
    }
    client.clearTokens()
}

export async function register(email, password) {
    return client.post('/users/register', { email, password })
}

export async function requestPasswordReset(email) {
    return client.post('/auth/password/request', { email })
}

export async function resetPassword(token, password) {
    return client.post('/auth/password/reset', { token, password })
}

export async function getCurrentUser() {
    const response = await client.get('/users/me', {
        fields: ['id', 'email', 'first_name', 'last_name', 'avatar', 'role.name', 'status', 'preferred_currency', 'preferred_locale']
    })
    return response.data
}

export async function updateCurrentUser(data) {
    const response = await client.patch('/users/me', data)
    return response.data
}
