import { Injectable, Logger, OnModuleInit } from "@nestjs/common"; import { InjectModel } from "@nestjs/mongoose"; import { FilterQuery, Model } from "mongoose"; import { HashService } from "src/utils/hash/hash.service"; import { SuperAdminModel, SuperAdminDocument, } from "../schema/super-admin.schema"; import { RoleEnum } from "src/Types&Enums/role.enum"; @Injectable() export class SuperAdminDbService implements OnModuleInit { private readonly logger = new Logger(SuperAdminDbService.name); constructor( @InjectModel(SuperAdminModel.name) private readonly superAdminModel: Model, private readonly hashService: HashService, ) {} /** * Seeds the default super-admin account on first boot. * Reads credentials from environment variables: * SUPER_ADMIN_EMAIL (default: super-admin@yara724.ir) * SUPER_ADMIN_PASSWORD (default: SuperAdmin@724) */ async onModuleInit() { const email = ( process.env.SUPER_ADMIN_EMAIL ?? "super-admin@yara724.ir" ).toLowerCase().trim(); const existing = await this.superAdminModel.findOne({ email }).lean(); if (existing) { this.logger.log(`Super-admin already exists (email=${email}), skipping seed.`); return; } const rawPassword = process.env.SUPER_ADMIN_PASSWORD ?? "SuperAdmin@724"; const password = await this.hashService.hash(rawPassword); await this.superAdminModel.create({ email, password, role: RoleEnum.SUPER_ADMIN, firstName: "Super", lastName: "Admin", }); this.logger.log(`Default super-admin seeded (email=${email}).`); } async findOne( filter: FilterQuery, ): Promise { return this.superAdminModel.findOne(filter).lean() as any; } async findByLoginIdentifier(identifier: string): Promise { const id = identifier.trim(); return this.superAdminModel.findOne({ email: id }).lean() as any; } async create(data: Partial): Promise { return this.superAdminModel.create(data); } async updateOne(filter: FilterQuery, update: any) { return this.superAdminModel.updateOne(filter, update); } async findAll(): Promise { return this.superAdminModel.find().lean() as any; } }