/**
 * API (REST) project generator.
 *
 * Wrapper fino sobre generateProject().
 * A lógica de geração comum (cópia, pub get, slang, build_runner, flutterfire)
 * vive em cli/lib/scaffold/generate.js.
 *
 * Hook específico (applyBackendSetup):
 *   1. Aplica api/patch/ sobre o template Firebase copiado
 *   2. Substitui pubspec.yaml pelo template API (pubspec.yaml.tpl)
 *   3. Remove artefatos Firebase exclusivos (feedbacks mantido — patch substitui as APIs)
 *   4. Escreve overrides de environment (apiBaseUrl)
 */

const path = require('node:path');
const fs = require('fs-extra');
const { applyPatch } = require('../../engine');
const { generateProject } = require('../../generate');
const { writeEnvironnementsOverrides } = require('../../shared/generator-utils');
const { removeBackendSpecificArtifacts } = require('../../shared/backend-config');

const API_PATCH_DIR = path.join(__dirname, 'patch');
const API_PUBSPEC = path.join(__dirname, 'pubspec.yaml.tpl');

async function generateApiProject(targetDir, options) {
  const { appName, bundleId, firebaseProjectId } = options;

  if (!appName || !bundleId || !firebaseProjectId) {
    throw new Error('generateApiProject requires appName, bundleId, firebaseProjectId');
  }

  return generateProject(targetDir, 'api', options, {
    applyBackendSetup: async (dir, tokens, pathReplacements, opts) => {
      // 1. Patch API (auth via HTTP, storage null, notifications via REST)
      const { filesApplied } = await applyPatch(API_PATCH_DIR, dir, tokens, pathReplacements);

      // 1b. README do backend (excluído do applyPatch) — copiar manualmente
      const language = opts.language ?? 'pt';
      const readmeLang = ['en', 'pt', 'es'].includes(language) ? language : 'en';
      const candidates = [
        path.join(API_PATCH_DIR, `README.${readmeLang}.md`),
        path.join(API_PATCH_DIR, 'README.md'),
      ];
      for (const src of candidates) {
        if (await fs.pathExists(src)) {
          await fs.copy(src, path.join(dir, 'README.md'));
          break;
        }
      }

      // 2. Substituir pubspec.yaml pelos deps do API backend
      const pubspecContent = await fs.readFile(API_PUBSPEC, 'utf8');
      let pubspecReplaced = pubspecContent;
      for (const [from, to] of Object.entries(tokens)) {
        pubspecReplaced = pubspecReplaced.replaceAll(from, to);
      }
      await fs.outputFile(path.join(dir, 'pubspec.yaml'), pubspecReplaced, 'utf8');

      // 3. Remover artefatos exclusivos do Firebase (feedbacks é mantido — patch API substitui as APIs)
      await removeBackendSpecificArtifacts(dir, 'api', opts.modules ?? []);

      // 4. Escrever overrides de environment com a URL da API
      await writeEnvironnementsOverrides(dir, 'api', tokens, { apiBaseUrl: opts.apiBaseUrl });

      return {
        detail: `${filesApplied} patch files`,
        extraAnswers: { apiBaseUrl: opts.apiBaseUrl },
        returnExtra: { apiBaseUrl: opts.apiBaseUrl },
      };
    },

    postBuild: null,
  });
}

module.exports = { generateApiProject, API_PATCH_DIR };
