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

// TypeORM CLI runs from apps/server/
const root = process.cwd();
config({ path: join(root, '.env') });

const dbType = process.env.DB_TYPE || 'sqlite';

export default new DataSource({
  type: dbType === 'mysql' ? 'mysql' : 'better-sqlite3',
  host: dbType === 'mysql' ? (process.env.DB_HOST || 'localhost') : undefined,
  port: dbType === 'mysql' ? (Number(process.env.DB_PORT) || 3306) : undefined,
  username: dbType === 'mysql' ? (process.env.DB_USERNAME || 'root') : undefined,
  password: dbType === 'mysql' ? (process.env.DB_PASSWORD || '') : undefined,
  database: process.env.DB_DATABASE || (dbType === 'mysql' ? 'dorm_billing' : 'dorm_billing.db'),
  charset: dbType === 'mysql' ? 'utf8mb4' : undefined,
  entities: [join(root, 'src/**/*.entity.ts')],
  migrations: [join(root, 'src/migrations/*.ts')],
});
