// @flow
import { getVersionInfo } from '../versionInfo';

import { IProvider, IVersionAndStoreUrl } from './types';

export type AppGalleryGetVersionOption = {
  packageName?: string,
  fetchOptions?: any,
  ignoreErrors?: boolean,
};

export interface IAppGalleryProvider extends IProvider {
  getVersion: AppGalleryGetVersionOption => Promise<IVersionAndStoreUrl>;
}

/**
 * HarmonyOS AppGallery provider.
 *
 * Unlike the App Store (iTunes Lookup API) and Google Play (page HTML), Huawei
 * AppGallery exposes NO public "lookup latest version" API. The app page
 * (`https://appgallery.huawei.com/app/{packageName}`) is JS-rendered, so
 * version extraction is strictly best-effort:
 *  - On a successful match the version is returned together with the fixed
 *    AppGallery store URL.
 *  - On failure the promise rejects with an explicit message so the caller can
 *    surface it. `getLatestVersion` / `needUpdate` swallow the rejection when
 *    `ignoreErrors` is true (the default), and consumers who need a reliable
 *    latest-version source should pass a custom provider.
 */
class AppGalleryProvider implements IProvider {
  getVersion(option: AppGalleryGetVersionOption): Promise<IVersionAndStoreUrl> {
    const opt = option || {};
    try {
      if (!opt.packageName) {
        opt.packageName = getVersionInfo().getPackageName();
      }

      const storeUrl = `https://appgallery.huawei.com/app/${opt.packageName}`;

      return fetch(storeUrl, opt.fetchOptions)
        .then(res => res.text())
        .then(text => {
          const match =
            text.match(/"versionName"\s*:\s*"([^"]+)"/) ||
            text.match(/versionName["']?\s*[:=]\s*["']([\d.]+)["']/i) ||
            text.match(/(\d+\.\d+\.\d+)/);
          if (match) {
            const latestVersion = match[1].trim();

            return Promise.resolve({ version: latestVersion, storeUrl });
          }

          return Promise.reject({
            message:
              'AppGallery has no public version lookup API; provide a custom provider.',
          });
        });
    } catch (e) {
      if (opt.ignoreErrors) {
        console.warn(e); // eslint-disable-line no-console
      } else {
        throw e;
      }
    }
  }
}

export default new AppGalleryProvider();