import { NestFactory } from "@nestjs/core";
import { AppModule } from "./app.module";
import * as cors from "cors";
// import * as dotenv from "dotenv";
// dotenv.config({ path: ".env.variables" });
import { DocumentBuilder, SwaggerModule } from "@nestjs/swagger";
async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  // Set 'trust proxy' using the underlying Express instance
  const expressApp = app.getHttpAdapter().getInstance();
  expressApp.set("trust proxy", true);
  // app.enableCors({
  //   origin: [
  //     "http://192.168.1.23",
  //     "https://dev-hms.plenome.com",
  //     "https://qa-hms.plenome.com",
  //     "https://demo-hms.plenome.com",
  //     "https://loadtest-hms.plenome.com",
  //     "https://uat-hms.plenome.com",
  //     "https://mountmsh.plenome.com",
  //   ],
  //   methods: ["GET", "POST", "PATCH", "DELETE"],
  //   allowedHeaders: ["Content-Type", "Authorization"],
  //   credentials: true, // important if cookies / auth headers are used
  // });

  app.enableCors({
    origin: (origin, callback) => {
      // Allow requests with no origin (mobile apps, curl, postman)
      if (!origin) {
        return callback(null, true);
      }

      try {
        const url = new URL(origin);
        const hostname = url.hostname;

        // Allow all subdomains of plenome.com
        if (hostname === "plenome.com" || hostname.endsWith(".plenome.com")) {
          return callback(null, true);
        }

        // Optional: allow localhost for development
        if (hostname === "localhost" || hostname.startsWith("192.168.")) {
          return callback(null, true);
        }

        return callback(new Error("Not allowed by CORS"), false);
      } catch (err) {
        return callback(new Error("Invalid origin"), false);
      }
    },
    credentials: true,
    methods: ["GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"],
    allowedHeaders: ["Content-Type", "Authorization"],
  });


  const config = new DocumentBuilder()
    .setTitle("OP-HUB API DOCUMENTATION")
    .setDescription("API SWAGGER DOCUMENTATION CREATED BY BACKEND DEVELOPERS")
    .setVersion("v1")
    .addTag(`appointment`)
    .build();

  const document = SwaggerModule.createDocument(app, config);
  SwaggerModule.setup("swagger-api/document", app, document);
  await app.listen(6001);
  console.log("Connected on port 6001");
}
bootstrap();
