/**
 * Centralized backend configuration: files/dirs to remove, post-copy behavior.
 * Single source of truth — add new backends here.
 *
 * @module scaffold/shared/backend-config
 */

const path = require('node:path');
const fs = require('fs-extra');

const FIREBASE_SOURCE_DIR = path.resolve(__dirname, '../../../templates/firebase');

/** Firebase-specific files not used by Supabase/API */
const FIREBASE_ONLY_FILES = [
  'lib/core/data/api/firestore_retry.dart',
  'lib/core/data/entities/json_converters.dart',
  // iOS native home-widget extension config (not needed without widget module)
  'ios/HomeWidgetExtension.entitlements',
  'home_widget_config.json',
];

/** iOS native home-widget extension — not needed for Supabase/API */
const HOME_WIDGET_IOS_EXTENSION_DIR = 'ios/HomeWidgetExtension';

/**
 * Get files to remove for a given backend.
 *
 * @param {'firebase'|'supabase'|'api'} backend
 * @returns {string[]}
 */
function getFilesToRemove(backend) {
  if (backend === 'firebase') return [];
  return [...FIREBASE_ONLY_FILES];
}

/**
 * Get directories to remove for a given backend.
 *
 * @param {'firebase'|'supabase'|'api'} backend
 * @param {string[]} [modules=[]] - Selected modules
 * @returns {string[]}
 */
function getDirsToRemove(backend, modules = []) {
  if (backend === 'firebase') return [];
  // home_widget works on all backends — only remove the iOS native extension
  return [HOME_WIDGET_IOS_EXTENSION_DIR];
}

/**
 * Remove files and directories from target project.
 *
 * @param {string} targetDir - Project root
 * @param {'firebase'|'supabase'|'api'} backend
 * @param {string[]} [modules=[]] - Selected modules
 */
async function removeBackendSpecificArtifacts(targetDir, backend, modules = []) {
  const { removeFiles } = require('../engine');

  await removeFiles(targetDir, getFilesToRemove(backend));

  for (const relDir of getDirsToRemove(backend, modules)) {
    const dirPath = path.join(targetDir, relDir);
    if (await fs.pathExists(dirPath)) {
      await fs.remove(dirPath);
    }
  }
}

module.exports = {
  FIREBASE_SOURCE_DIR,
  getFilesToRemove,
  getDirsToRemove,
  removeBackendSpecificArtifacts,
};
