import { config } from 'dotenv';
import { resolve } from 'path';
import { DataSource } from 'typeorm';

// npm workspace scripts (`db:migrate`, `db:seed`) run with this file's
// workspace (`apps/api`) as the current working directory, not the repo
// root where the documented `.env` lives. Resolve it explicitly so the
// documented `npm run db:migrate` / `npm run db:seed` flow works regardless
// of the caller's working directory.
config({ path: resolve(__dirname, '../../../../.env') });

const databaseUrl = process.env.DATABASE_URL;

if (!databaseUrl?.trim()) {
  throw new Error('DATABASE_URL is required');
}

export const AppDataSource = new DataSource({
  type: 'postgres',
  url: databaseUrl,
  entities: [__dirname + '/../**/*.entity.{ts,js}'],
  migrations: [__dirname + '/migrations/[0-9]*.{ts,js}'],
  synchronize: false,
});
