import {
  Injectable,
  Logger,
  OnApplicationShutdown,
  OnModuleInit,
} from "@nestjs/common";
import { closeDb } from "../../config/database.js";
import { closeNeo4j } from "../../config/neo4j.js";

const SERVICE_NAME = "content";

@Injectable()
export class LifecycleService implements OnModuleInit, OnApplicationShutdown {
  private readonly logger = new Logger(LifecycleService.name);

  onModuleInit(): void {
    this.logger.log(`service ${SERVICE_NAME} module initialized`);
  }

  async onApplicationShutdown(signal?: string): Promise<void> {
    this.logger.log(
      `service ${SERVICE_NAME} shutting down (signal=${signal ?? "unknown"})`,
    );
    try {
      await closeNeo4j();
      await closeDb();
      this.logger.log(`service ${SERVICE_NAME} shutdown complete`);
    } catch (error) {
      this.logger.error(
        `shutdown failed: ${error instanceof Error ? error.message : String(error)}`,
      );
    }
  }
}
