/**
 * Backend .env Generator
 *
 * Generates .env file for backend workspace
 */

import type { TemplateContext } from '@specverse/types';

export default function generateBackendEnv(context: TemplateContext): string {
  const { spec, manifest } = context;

  const projectName = (spec.metadata?.component || 'app')
    .toLowerCase()
    .replace(/\s+/g, '-');

  // Read database config from the dev environment. Prefer `development`,
  // else the first environment that declares a database (e.g. a `smoke`
  // env). This selection MUST stay identical to realize's schema threading
  // (#75) so the .env and the prisma datasource agree on the provider —
  // otherwise `prisma db push` fails on a provider/url mismatch.
  const environments = (manifest as any)?.configuration?.environments || {};
  const devEnv: any = environments.development?.database
    ? environments.development
    : Object.values(environments).find((e: any) => e?.database) || {};
  const dbConfig = devEnv.database || {};
  const provider: string = dbConfig.provider || 'sqlite';
  const databaseUrl: string = dbConfig.url ||
    (provider === 'sqlite' ? 'file:./dev.db' : `postgresql://${process.env.USER || 'postgres'}:@localhost:5432/spv_${projectName}_dev`);

  // Read port from the same environment if available.
  const port = devEnv.server?.port || 3000;

  return `# Backend Environment Configuration
# Database
DATABASE_URL="${databaseUrl}"

# API Configuration
PORT=${port}
HOST=0.0.0.0
NODE_ENV=development

# CORS
CORS_ORIGINS="http://localhost:5173"

# Prisma — suppress the "new major version available" banner that
# otherwise prints after every prisma command. Remove this line if
# you want the upgrade nag back.
PRISMA_HIDE_UPDATE_MESSAGE=true
`;
}
