import { TypeOrmModuleOptions } from '@nestjs/typeorm';
import * as path from 'path';

/**
 * TypeORM DataSource options for the shared `iam` schema.
 *
 * Context (see docs/iam-package-understanding-guide.md):
 * - The `iam` schema is owned by `@tria-plc/iamapi-common` (TypeORM). Prisma owns the
 *   `passenger` schema. Both ORMs point at the same database (`edr_database`).
 * - `@tria-plc/api-common`'s `JwtGuard` injects the *default* TypeORM `DataSource` and runs a
 *   raw `SELECT ... FROM iam.sessions`, so the app must expose a DataSource that can reach it.
 *
 * Connection env vars intentionally mirror the package's own migration DataSource
 * (`@tria-plc/api-common/dist/modules/typeorm/typeorm.config.internal.js`) so the app and the
 * package CLI read the same configuration:
 *   DATABASE_HOST, DATABASE_PORT, DATABASE_NAME, DATABASE_USER, DATABASE_PASSWORD, DATABASE_SCHEMA
 *
 * This NEVER manages the schema: `synchronize: false` and `migrationsRun: false`. The `iam`
 * schema is created by the IAM package migrations (dev: self-hosted; prod: central IAM team).
 */
function resolvePackageDist(pkg: string): string {
  // Node honors each package's `exports` map at runtime even though TS `moduleResolution: "Node"`
  // does not — so `require.resolve` on the barrel resolves to the package's dist `index.js`.
  const resolved = require.resolve(pkg);
  // Normalize to forward slashes so the glob works on Windows too.
  return path.dirname(resolved).replace(/\\/g, '/');
}

export function buildIamTypeOrmOptions(): TypeOrmModuleOptions {
  const iamDist = resolvePackageDist('@tria-plc/iamapi-common');
  // Some IAM entities (e.g. PositionType) relate to the notification entities that physically
  // live in @tria-plc/api-common (the IAM barrel only re-exports them), so BOTH dist trees must
  // be registered or TypeORM throws "Entity metadata ... was not found".
  const apiDist = resolvePackageDist('@tria-plc/api-common');
  return {
    type: 'postgres',
    host: process.env.DATABASE_HOST,
    port: Number(process.env.DATABASE_PORT ?? 5432),
    database: process.env.DATABASE_NAME,
    username: process.env.DATABASE_USER,
    password: process.env.DATABASE_PASSWORD,
    schema: process.env.DATABASE_SCHEMA ?? 'iam',
    // IAM entities live in the packages; registered so the same default DataSource also serves
    // IamModule in the dev self-host phase (Phase 3). Harmless before the tables exist.
    entities: [
      `${iamDist}/entities/**/*.entity.{ts,js}`,
      `${apiDist}/entities/**/*.entity.{ts,js}`,
    ],
    synchronize: false,
    migrationsRun: false,
    autoLoadEntities: false,
    migrationsTableName: 'typeorm_migrations',
    retryAttempts: process.env.IAM_ENABLED === 'true' ? 3 : 0,
    logging: ['error'],
  };
}
