import { DataSource } from "typeorm";
import { pgsql, printConfigSummary } from "../config";
import * as entities from "./entities";

printConfigSummary();

export const AppDataSource = new DataSource({
    type: "postgres",
    host: pgsql.host,
    port: pgsql.port,
    database: pgsql.database,
    username: pgsql.user,
    password: pgsql.password,
    // 实体注册：关系实体通过 entities/index.ts 统一导出
    // TimescaleDB K 线实体后续通过 @timescaledb/typeorm 装饰器注册
    entities: [
        ...Object.values(entities),
    ],
    // 生产环境禁用 synchronize，使用 Migration
    synchronize: false,
    migrations: [__dirname + "/migrations/*.{ts,js}"],
    // 连接池
    extra: {
        max: pgsql.max,                        // 最大连接数 20
        idleTimeoutMillis: pgsql.idleTimeoutMillis, // 空闲超时 30s
        connectionTimeoutMillis: pgsql.connectionTimeoutMillis, // 连接超时 5s
    },
    logging: process.env.NODE_ENV === "development" ? ["error", "warn"] : ["error"],
});

await AppDataSource.initialize();