import { registerAs } from "@nestjs/config";
import { TypeOrmModuleOptions } from "@nestjs/typeorm";
import { DataSourceOptions } from "typeorm";

/**
 * Shared connection options for the Nest TypeORM module and the standalone DataSource
 * (migration CLI). Payment tables live in the SAME Postgres database as the domain system
 * (edr_database by default) but in the dedicated `edr_payment` schema; logical ownership is
 * enforced with a dedicated DB user in non-dev environments (grants only on this schema).
 */
export function buildDataSourceOptions(): DataSourceOptions {
  return {
    type: "postgres",
    host: process.env.DB_HOST ?? "localhost",
    port: parseInt(process.env.DB_PORT ?? "5432", 10),
    username: process.env.DB_USER ?? "edr",
    password: process.env.DB_PASSWORD ?? "",
    database: process.env.DB_NAME ?? "edr_database",
    schema: process.env.DB_SCHEMA ?? "edr_payment",
    entities: [__dirname + "/../**/*.entity.{ts,js}"],
    migrations: [__dirname + "/../migrations/*.{ts,js}"],
    // Schema changes go through migrations only — never synchronize (house rule).
    synchronize: false,
    logging: process.env.NODE_ENV === "development",
  };
}

export default registerAs(
  "database",
  (): TypeOrmModuleOptions => ({
    ...buildDataSourceOptions(),
    autoLoadEntities: true,
    // Run pending migrations on boot (main.ts ensures the database/schema exist first).
    migrationsRun: true,
  }),
);
