import { request } from './request'
import { MINI_PROGRAM_ID } from '@/config'
import { storage, SESSION_KEY, USER_KEY } from '@/utils/storage'

export async function login() {
	return new Promise((resolve, reject) => {
		uni.login({
			provider: 'weixin',
			success: async (loginRes) => {
				try {
					const res = await request.post('/auth/login', {
						mini_program_id: MINI_PROGRAM_ID,
						code: loginRes.code
					})

					storage.set(SESSION_KEY, res.data.session_key)
					storage.set(USER_KEY, res.data.user)

					resolve(res.data)
				} catch (e) {
					reject(e)
				}
			},
			fail: (err) => {
				reject(err)
			}
		})
	})
}

export function getUser() {
	return storage.get(USER_KEY)
}

export function getSessionKey() {
	return storage.get(SESSION_KEY)
}

export function isLoggedIn() {
	return !!getSessionKey()
}

export function logout() {
	storage.remove(SESSION_KEY)
	storage.remove(USER_KEY)
}
