import { registerAs } from "@nestjs/config";
import { TypeOrmModuleOptions } from "@nestjs/typeorm";
import { join, dirname } from "path";
import {
  DefaultPosition,
  DefaultUnit,
  EmployeePosition,
  Employee,
  OrganizationConfiguration,
  GlobalOrganizationConfiguration,
  OrganizationType,
  Organization,
  PositionConfiguration,
  PositionPermission,
  PositionTypeConfiguration,
  PositionTypePermission,
  PositionType,
  Position,
  Project,
  GlobalUnitConfiguration,
  Unit,
  EmployeeSignature,
  EmployeeStamp,
  RecordFooter,
  RecordHeader,
  Seal,
  AccountConfiguration,
  Application,
  DocumentaryRequirement,
  Permission,
  RolePermission,
  Role,
  Session,
  UserCredential,
  UserDocument,
  UserRole,
  UserVerification,
  User,
  Notification,
  NotificationEvent,
  NotificationPlaceholder,
  NotificationReceiverField,
  NotificationReceiver,
  NotificationTemplate,
} from "@tria-plc/iamapi-common";
import { OrganizationSetting } from "@tria-plc/iamapi-common/entities/iam/organization-structure/organization-setting.entity";

const iamEntities = [
  DefaultPosition,
  DefaultUnit,
  EmployeePosition,
  Employee,
  OrganizationConfiguration,
  GlobalOrganizationConfiguration,
  OrganizationSetting,
  OrganizationType,
  Organization,
  PositionConfiguration,
  PositionPermission,
  PositionTypeConfiguration,
  PositionTypePermission,
  PositionType,
  Position,
  Project,
  GlobalUnitConfiguration,
  Unit,
  EmployeeSignature,
  EmployeeStamp,
  RecordFooter,
  RecordHeader,
  Seal,
  AccountConfiguration,
  Application,
  DocumentaryRequirement,
  Permission,
  RolePermission,
  Role,
  Session,
  UserCredential,
  UserDocument,
  UserRole,
  UserVerification,
  User,
  Notification,
  NotificationEvent,
  NotificationPlaceholder,
  NotificationReceiverField,
  NotificationReceiver,
  NotificationTemplate,
];

const iamMigrationsGlob = join(
  dirname(require.resolve("@tria-plc/iamapi-common/package.json")),
  "dist/db/migrations/*.js",
);
const freightMigrationsGlob = join(__dirname, "../migrations/*.js");

export default registerAs("database", (): TypeOrmModuleOptions => {
  return {
    type: "postgres",
    host: process.env.DB_HOST ?? "localhost",
    port: parseInt(process.env.DB_PORT ?? "5433", 10),
    username: process.env.DB_USER ?? "postgres",
    password: process.env.DB_PASSWORD ?? "",
    database: process.env.DB_NAME ?? "edr_freight",
    schema: "public",
    // NOTE: do NOT pass `extra.options: '-c search_path=...'`. That sends the
    // Postgres startup `options` parameter, which connection poolers (PgBouncer /
    // proxies fronting the remote edr_dev DB) reject with
    // `08P01 unsupported startup parameter in options: search_path`.
    // The search_path is instead applied per-connection via a pool `connect`
    // handler in app.module.ts (see setPoolSearchPath).
    entities: [__dirname + "/../**/*.entity.{ts,js}", ...iamEntities],
    autoLoadEntities: true,
    migrations: [
      // IAM schema + tables must be created before freight migrations
      iamMigrationsGlob,
      freightMigrationsGlob,
    ],
    migrationsRun: true,
    migrationsTransactionMode: "each",
    // Schema changes via migrations only (synchronize breaks ITMLS backfill on existing rows).
    synchronize: false,
    logging:
      process.env.TYPEORM_LOGGING === "true" ? true : ["error", "warn"],
  };
});
