import "dotenv/config";
import "reflect-metadata";
import { DataSource, Logger, QueryRunner } from "typeorm";
import { RequestWithUser } from "../middlewares/user";
import { addLogSequence } from "../interfaces/utils";

export class MyCustomLogger implements Logger {
  log(level: "log" | "info" | "warn", message: any, queryRunner?: QueryRunner) {}

  logQuery(query: string, parameters?: any[], queryRunner?: QueryRunner): void {
    const req = queryRunner?.data as RequestWithUser;
    if (req?.app?.locals.logData?.sequence) {
      addLogSequence(req, {
        action: "database",
        status: "success",
        description: "Query Data.",
        query: [
          "Query: " + query + (parameters ? " - Parameters:" + JSON.stringify(parameters) : ""),
        ],
      });
    }
  }

  logMigration(message: string, queryRunner?: QueryRunner) {}
  logQueryError(
    error: string | Error,
    query: string,
    parameters?: any[],
    queryRunner?: QueryRunner,
  ) {}
  logQuerySlow(time: number, query: string, parameters?: any[], queryRunner?: QueryRunner) {}
  logSchemaBuild(message: string, queryRunner?: QueryRunner) {}
}

export const AppDataSource = new DataSource({
  type: "mysql",
  // extra: {
  //   timezone: "+07:00", // Bangkok timezone (UTC+7)
  // },
  database: process.env.DB_NAME,
  host: process.env.DB_HOST,
  port: +(process.env.DB_PORT || 3306),
  username: process.env.DB_USERNAME,
  password: process.env.DB_PASSWORD,
  connectorPackage: "mysql2",
  synchronize: false,
  logging: true,
  //   timezone: "Z",
  entities:
    process.env.NODE_ENV !== "production"
      ? ["src/entities/**/*.ts"]
      : ["dist/entities/**/*{.ts,.js}"],
  migrations:
    process.env.NODE_ENV !== "production"
      ? ["src/migration/**/*.ts"]
      : ["dist/migration/**/*{.ts,.js}"],
  subscribers: [],
  logger: new MyCustomLogger(),
  // Connection pool settings to prevent connection exhaustion
  extra: {
    connectionLimit: +(process.env.DB_CONNECTION_LIMIT || 50),
    maxIdle: +(process.env.DB_MAX_IDLE || 10),
    idleTimeout: +(process.env.DB_IDLE_TIMEOUT || 60000),
    timezone: "+07:00", // Bangkok timezone (UTC+7)
  },
  // TypeORM pool settings
  poolSize: +(process.env.DB_POOL_SIZE || 10),
  maxQueryExecutionTime: +(process.env.DB_MAX_QUERY_TIME || 3000),
});

// export default database;
