import { NestFactory } from '@nestjs/core'
import { AppModule } from './app.module'

function configuredOrigins() {
  const raw = process.env.CORS_ALLOW_ORIGINS || process.env.FRONTEND_ORIGIN || process.env.WEB_ORIGIN || 'http://localhost:3000'
  return raw.split(',').map((item) => item.trim()).filter(Boolean)
}

async function bootstrap() {
  const app = await NestFactory.create(AppModule)
  const port = Number(process.env.PORT ?? 4000)
  const isProduction = process.env.NODE_ENV === 'production'
  const allowedOrigins = configuredOrigins()

  app.enableCors({
    origin: isProduction
      ? (origin: string | undefined, callback: (error: Error | null, allow?: boolean) => void) => {
          if (!origin || allowedOrigins.includes(origin)) {
            callback(null, true)
            return
          }
          callback(new Error('CORS origin denied'), false)
        }
      : true,
    credentials: true,
  })
  app.setGlobalPrefix('api')

  await app.listen(port)
}

void bootstrap()
