import request from './utils/request';

App({
    onLaunch() {
        // Initialize login process immediately
        this.loginPromise = new Promise((resolve, reject) => {
            this._resolveLogin = resolve;
            this._rejectLogin = reject;
        });

        this.doLogin();
    },

    // Perform actual login
    doLogin() {
        wx.login({
            success: res => {
                if (res.code) {
                    request.post('/auth/miniLogin', { code: res.code, clientId: 'sundynix-plant' }).then(async (data) => {
                        const token = data.token;

                        if (token && typeof token === 'string') {
                            wx.setStorageSync('token', token);

                            if (this._resolveLogin) this._resolveLogin(token);

                            // Background Profile Update
                            request.get('/plant/profile/detail').then(userDetail => {
                                if (userDetail) {
                                    wx.setStorageSync('userInfo', userDetail);
                                    this.globalData.userInfo = userDetail;
                                }
                            }).catch(e => {
                                console.error('Fetch profile detail failed on launch', e);
                                // Fallback
                                if (data.user) {
                                    wx.setStorageSync('userInfo', data.user);
                                    this.globalData.userInfo = data.user;
                                }
                            });
                        } else {
                            console.warn('Login response invalid', data);
                            if (this._rejectLogin) this._rejectLogin('No token');
                        }
                    }).catch(err => {
                        console.error('Login API failed', err);
                        if (this._rejectLogin) this._rejectLogin(err);
                    });
                } else {
                    console.error('wx.login failed: ' + res.errMsg);
                    if (this._rejectLogin) this._rejectLogin(res.errMsg);
                }
            },
            fail: err => {
                if (this._rejectLogin) this._rejectLogin(err);
            }
        });
    },

    // Force refresh login (e.g. on 401)
    forceRefreshLogin() {
        // Reset Promise
        this.loginPromise = new Promise((resolve, reject) => {
            this._resolveLogin = resolve;
            this._rejectLogin = reject;
        });
        wx.removeStorageSync('token');
        this.doLogin();
        return this.loginPromise;
    },

    // Method for other pages/utils to wait for login
    ensureLogin() {
        // If token exists, resolve immediately
        const token = wx.getStorageSync('token');
        if (token) return Promise.resolve(token);

        // Return existing promise or create new if failed previously?
        // For simplicity, return the launch promise. 
        // In robust apps, handle token expiration and re-login here.
        return this.loginPromise;
    },
    globalData: {
        userInfo: null
    }
})
