import Constants from 'expo-constants';
import * as Linking from 'expo-linking';
import { Alert, Platform, BackHandler } from 'react-native';
import * as Updates from 'expo-updates';

export function checkVersion(fetchedVersion: { version: string; isActive: boolean }) {
    const currentVersion = Constants.expoConfig?.version;
    // console.log('currentVersion', currentVersion);
    // console.log('fetchedVersion', fetchedVersion.version);
    // console.log('fetchedVersion.isActive', fetchedVersion.isActive);
    if (!fetchedVersion.isActive) {
        Alert.alert(
            '伺服器維護中，敬請見諒',
            '',
            [
                {
                    text: '確認',
                    onPress: () => {
                        if (Platform.OS === 'android') {
                            BackHandler.exitApp();
                        } else {
                            // For iOS, we can force a reload of the app
                            // This will create an infinite loop of the maintenance message
                            // until maintenance is over
                            setTimeout(() => {
                                Updates.reloadAsync();
                            }, 100);
                        }
                    }
                }
            ],
            { cancelable: false }
        );
        // Prevent any further code execution
        throw new Error('MAINTENANCE_MODE');
    }

    if (currentVersion && currentVersion !== fetchedVersion.version) {
        Alert.alert(
            '請更新到最新版本',
            'Please update to the latest version of the app to continue.',
            [
                {
                    text: '現在更新',
                    onPress: () => {
                        const url =
                            Platform.OS === 'ios'
                                ? 'https://apps.apple.com/app/crazy-charge/id6639612402'
                                : 'https://play.google.com/store/apps/details?id=hk.com.crazycharge';
                        Linking.openURL(url);
                    }
                }
            ],
            { cancelable: false }
        );
    }
}
