import { Injectable, OnApplicationBootstrap, Logger } from '@nestjs/common'; import { UserService } from './service/user.service'; import { RoleService } from '../role/service/role.service'; @Injectable() export class DatabaseSeedService implements OnApplicationBootstrap { private readonly logger = new Logger(DatabaseSeedService.name); constructor( private readonly userService: UserService, private readonly roleService: RoleService, ) {} async onApplicationBootstrap() { await this.seedUsers(); } private async seedUsers() { try { const isProduction = process.env.NODE_ENV === 'production'; const allPermissions = [ '*', 'read:cabin', 'create:cabin', 'update:cabin', 'delete:cabin', 'read:company', 'create:company', 'update:company', 'delete:company', 'read:role', 'create:role', 'update:role', 'delete:role', 'manage:permissions' ]; // 1. Criar Perfil Administrador se não existir let adminRole = await this.roleService.findByName('Administrador'); if (!adminRole) { this.logger.log('Semente: Criando Perfil Administrador...'); adminRole = await this.roleService.create({ name: 'Administrador', permissions: allPermissions, }); } else if (!adminRole.permissions.includes('*')) { this.logger.log('Semente: Atualizando Perfil Administrador com curinga *...'); adminRole = await this.roleService.update(adminRole.id, { permissions: [...new Set(['*', ...adminRole.permissions])], }); } // 2. Criar Perfil Usuário Comum se não existir (apenas se não for produção) let userRole = await this.roleService.findByName('Usuário Comum'); if (!userRole && !isProduction) { this.logger.log('Semente: Criando Perfil Usuário Comum...'); userRole = await this.roleService.create({ name: 'Usuário Comum', permissions: ['read:cabin', 'read:company'], }); } // 3. Admin Inicial das Envs const adminEmail = process.env.ADMIN_EMAIL || 'admin@devstroupe.com'; const adminPassword = process.env.ADMIN_PASSWORD; if (isProduction && !process.env.ADMIN_PASSWORD) { this.logger.error('Semente: ERRO! A variável de ambiente ADMIN_PASSWORD precisa ser definida em produção.'); throw new Error('ADMIN_PASSWORD não configurada em produção.'); } const existingAdmin = await this.userService.findByEmail(adminEmail); if (!existingAdmin) { this.logger.log('Semente: Criando usuário administrador...'); await this.userService.create({ name: 'Administrador', email: adminEmail, password: adminPassword || 'adminpassword123', role: adminRole, isActive: true, createdAt: new Date(), updatedAt: new Date() }); this.logger.log('Semente: Usuário administrador cadastrado com sucesso!'); } // 4. Criar Usuário Comum apenas se não for ambiente de produção if (!isProduction) { const userEmail = 'user@devstroupe.com'; const existingUser = await this.userService.findByEmail(userEmail); if (!existingUser && userRole) { this.logger.log('Semente: Criando usuário comum padrão...'); await this.userService.create({ name: 'Usuário Comum', email: userEmail, password: 'userpassword123', role: userRole, isActive: true, createdAt: new Date(), updatedAt: new Date() }); this.logger.log('Semente: Usuário comum cadastrado com sucesso!'); } } } catch (error) { this.logger.error('Erro durante a execução do seeding de usuários:', error); } } }