import { Injectable, Logger, OnModuleInit } from "@nestjs/common";
import { PrismaService } from "../prisma/prisma.service";
import { ConfigService } from "@nestjs/config";
import * as bcrypt from "bcrypt";

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

  constructor(
    private readonly prisma: PrismaService,
    private readonly configService: ConfigService,
  ) {}

  async onModuleInit() {
    this.logger.log("Initializing application and creating default admin...");
    await this.initializeSystem();
  }

  async initializeSystem() {
    this.logger.log("Starting system initialization...");

    const defaultAdminEmail =
      this.configService.get("DEFAULT_ADMIN_EMAIL") || "taratur@gmail.com";
    const defaultAdminPassword =
      this.configService.get("DEFAULT_ADMIN_PASSWORD") || "irina7654321";
    const defaultAdminName =
      this.configService.get("DEFAULT_ADMIN_NAME") || "System Admin";

    try {
      this.logger.log("Checking for existing admin user...");
      // Check if admin already exists
      const existingAdmin = await this.prisma.user.findUnique({
        where: { email: defaultAdminEmail },
      });

      if (!existingAdmin) {
        this.logger.log("No admin found. Creating default admin user...");
        // Hash the password
        const hashedPassword = await bcrypt.hash(defaultAdminPassword, 10);

        // Create the admin user
        const admin = await this.prisma.user.create({
          data: {
            email: defaultAdminEmail,
            name: defaultAdminName,
            password: hashedPassword,
            isAdmin: true,
          },
        });

        this.logger.log("Default admin user created successfully", {
          id: admin.id,
          email: admin.email,
          name: admin.name,
        });

        return {
          success: true,
          message: "System initialized successfully",
          admin: {
            id: admin.id,
            email: admin.email,
            name: admin.name,
          },
        };
      }

      this.logger.log("Default admin user already exists", {
        id: existingAdmin.id,
        email: existingAdmin.email,
        name: existingAdmin.name,
      });

      return {
        success: true,
        message: "System already initialized",
        admin: {
          id: existingAdmin.id,
          email: existingAdmin.email,
          name: existingAdmin.name,
        },
      };
    } catch (error) {
      this.logger.error("Error during system initialization:", error);
      throw error;
    }
  }
}
