/**
 * Token replacement map for the base Flutter template (Firebase/).
 *
 * All backends (Firebase, Supabase, API) start from the same Firebase/ template,
 * so all generators import buildTokens from this file. The tokens describe the
 * hardcoded placeholder values that exist in the template source and that are
 * substituted with the user's actual app name, bundle ID, and credentials at
 * generation time.
 *
 * Original hardcoded values in Firebase/:
 *   - package name  : kasy_kit       (Dart import path prefix)
 *   - bundle ID     : com.aicrus.firebase.kit (Android namespace, iOS bundle ID)
 *   - app display   : Kasy App                (AndroidManifest, Info.plist) — unique string with space, won't collide with KasyButton/KasyTheme/etc
 *   - short name    : appfirebase             (kAppName Dart constant)
 */

const ORIGINAL_PACKAGE = 'kasy_kit';
const ORIGINAL_BUNDLE_ID = 'com.aicrus.firebase.kit';
const ORIGINAL_APP_NAME = 'Kasy App';
const ORIGINAL_SHORT_NAME = 'appfirebase';

/**
 * Normalize app name to a valid Dart package name.
 * "Meu App Incrível" → "meu_app_incrivel"
 */
function toPackageName(appName) {
  return (appName || '')
    .normalize('NFD')
    .replace(/[\u0300-\u036f]/g, '')   // remove accents
    .trim()
    .toLowerCase()
    .replace(/[^a-z0-9]/g, '_')
    .replace(/_+/g, '_')
    .replace(/^[^a-z]+/, 'app_')
    .replace(/_+$/, '') || 'my_app';
}

/**
 * Short name without underscores, used in kAppName constant.
 * "meu_app" → "meuapp"
 */
function toShortName(packageName) {
  return packageName.replace(/_/g, '');
}

/**
 * Convert bundle ID to Android Kotlin path (com.example.app → com/example/app).
 */
function bundleIdToPath(bundleId) {
  return (bundleId || '').replace(/\./g, '/');
}

const ORIGINAL_BUNDLE_ID_PATH = bundleIdToPath(ORIGINAL_BUNDLE_ID);

// Facebook — só caracteres permitidos no URL scheme da Apple (RFC1738).
// Sem credenciais no `kasy new`, mantém estes placeholders (login FB não funciona até trocar).
const FB_APP_ID_PLACEHOLDER = '000000000000000';
const FB_CLIENT_TOKEN_PLACEHOLDER = '00000000000000000000000000000000';

const PAYWALL_TOKEN = '__PAYWALL_FACTORY__';

/**
 * Build the full token replacement map given user answers.
 *
 * @param {object} params
 * @param {string} params.appName
 * @param {string} params.bundleId
 * @param {string} [params.fbAppId] - Facebook App ID (when module selected)
 * @param {string} [params.fbToken] - Facebook Client Token (when module selected)
 * @param {string} [params.defaultPaywall] - PaywallFactory.basic | .minimal | .withSwitch | .basicRow
 * @param {string} [params.functionsRegion] - GCP region for Cloud Functions (e.g. southamerica-east1)
 * @returns {{ tokens: Record<string,string>, packageName: string, shortName: string, pathReplacements: Record<string,string> }}
 */
function buildTokens({ appName, bundleId, fbAppId, fbToken, defaultPaywall = 'basic', functionsRegion = 'us-central1' }) {
  const packageName = toPackageName(appName);
  const shortName = toShortName(packageName);

  const paywallFactory = ['basic', 'minimal', 'withSwitch', 'basicRow'].includes(defaultPaywall)
    ? `PaywallFactory.${defaultPaywall}`
    : 'PaywallFactory.basic';

  const tokens = {
    // Dart import paths
    [`package:${ORIGINAL_PACKAGE}/`]: `package:${packageName}/`,
    // Android namespace / applicationId
    [ORIGINAL_BUNDLE_ID]: bundleId,
    // App display name in native (Android manifest, iOS plist, etc.)
    [ORIGINAL_APP_NAME]: appName,
    // kAppName constant in Dart (quoted — both single and double)
    [`'${ORIGINAL_SHORT_NAME}'`]: `'${shortName}'`,
    [`"${ORIGINAL_SHORT_NAME}"`]: `"${shortName}"`,
    // pubspec.yaml name field
    [`name: ${ORIGINAL_PACKAGE}`]: `name: ${packageName}`,
    // Facebook (placeholders → user values ou mantém placeholder válido p/ App Store)
    [FB_APP_ID_PLACEHOLDER]: fbAppId?.trim() || FB_APP_ID_PLACEHOLDER,
    [`fb${FB_APP_ID_PLACEHOLDER}`]: fbAppId?.trim() ? `fb${fbAppId.trim()}` : `fb${FB_APP_ID_PLACEHOLDER}`,
    [FB_CLIENT_TOKEN_PLACEHOLDER]: fbToken?.trim() || FB_CLIENT_TOKEN_PLACEHOLDER,
    [PAYWALL_TOKEN]: paywallFactory,
    // Cloud Functions region — injected into functions/src/index.ts
    'europe-west1': functionsRegion,
  };

  // Path replacements so Android Kotlin package folder matches bundle ID
  // e.g. android/.../kotlin/com/appfirebase/app/ → android/.../kotlin/com/example/myapp/
  const pathReplacements = {};
  if (bundleId && bundleId !== ORIGINAL_BUNDLE_ID) {
    pathReplacements[ORIGINAL_BUNDLE_ID_PATH] = bundleIdToPath(bundleId);
  }

  return { tokens, packageName, shortName, pathReplacements };
}

module.exports = { buildTokens, toPackageName, toShortName, bundleIdToPath, PAYWALL_TOKEN };
