/*
 * Copyright (C) 2022 StApps
 * This program is free software: you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by the Free
 * Software Foundation, version 3.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
 * more details.
 *
 * You should have received a copy of the GNU General Public License along with
 * this program. If not, see <https://www.gnu.org/licenses/>.
 */

import {AuthorizationServiceConfigurationJson} from '@openid/appauth';
import {IAuthConfig} from 'ionic-appauth';
import {SCAuthorizationProvider, SCAuthorizationProviderType} from '@openstapps/core';
import {Capacitor} from '@capacitor/core';
import {authPaths} from './auth-paths';
import {environment} from '../../../environments/environment';

/**
 * Get configuration of an OAuth2 client
 */
export function getClientConfig(
  providerType: SCAuthorizationProviderType,
  authConfig: {
    default?: SCAuthorizationProvider;
    paia?: SCAuthorizationProvider;
  },
): IAuthConfig {
  const providerConfig = authConfig[providerType] as SCAuthorizationProvider;
  return {
    end_session_redirect_url: '',
    pkce: true,
    scopes: providerConfig.client.scopes,
    server_host: providerConfig.client.url,
    client_id: providerConfig.client.clientId,
    redirect_url: getRedirectUrl(authPaths[providerType].redirect_path),
  };
}

/**
 * Get configuration about endpoints of an OAuth2 server
 */
export function getEndpointsConfig(
  providerType: SCAuthorizationProviderType,
  authConfig: {
    default?: SCAuthorizationProvider;
    paia?: SCAuthorizationProvider;
  },
): AuthorizationServiceConfigurationJson {
  const providerConfig = authConfig[providerType] as SCAuthorizationProvider;
  return {
    authorization_endpoint: providerConfig.endpoints.authorization,
    end_session_endpoint: providerConfig.endpoints.endSession,
    revocation_endpoint: providerConfig.endpoints.revoke ?? '',
    token_endpoint: providerConfig.endpoints.token,
    userinfo_endpoint: providerConfig.endpoints.userinfo,
  };
}

/**
 * Return a URL of the app, depending on the platform where it is running
 */
function getRedirectUrl(routePath: string): string {
  let appHost: string;
  let appSchema: string;
  if (environment.production) {
    appSchema = Capacitor.isNativePlatform() ? environment.custom_url_scheme : 'https';
    appHost = environment.app_host;
  } else {
    appSchema = Capacitor.isNativePlatform()
      ? environment.custom_url_scheme
      : window.location.protocol.split(':')[0];

    appHost = Capacitor.isNativePlatform() ? environment.app_host : window.location.host;
  }
  return `${appSchema}://${appHost}/${routePath}`;
}
