import { EntityManager } from '@mikro-orm/core';
import { User } from '@/apps/_app/entities/user/_User';
import { UserRole } from '@/apps/_app/entities/user/UserRole';
import { PLATFORMROLES, UserRoleType } from '@/constants/roles';
import bcrypt from 'bcrypt';

interface SeedUser {
    username: string;
    email: string;
    password: string;
    role: UserRoleType;
}

export class UserSeed {
    private readonly seedUsers: SeedUser[] = [
        {
            username: process.env.DEFAULT_ADMIN_USERNAME || 'liquidrinu',
            email: process.env.DEFAULT_ADMIN_EMAIL || 'liquidrinu@gmail.com',
            password: process.env.DEFAULT_ADMIN_PASSWORD || 'admin123',
            role: PLATFORMROLES.Admin as UserRoleType
        }
    ];

    constructor(private readonly em: EntityManager) {}

    async run() {
        console.log('Seeding users...');

        for (const seedUser of this.seedUsers) {
            const existingUser = await this.em.findOne(User, { username: seedUser.username });
            
            if (!existingUser) {
                const user = new User();
                user.username = seedUser.username;
                user.email = seedUser.email;
                user.password = await bcrypt.hash(seedUser.password, 12);

                const role = await this.em.findOne(UserRole, { name: seedUser.role });
                if (!role) {
                    throw new Error(`Role ${seedUser.role} not found. Please run RoleSeed first.`);
                }

                user.roles.add(role);
                await this.em.persistAndFlush(user);
                console.log(`Created user: ${seedUser.username} with role ${seedUser.role}`);
            } else {
                console.log(`User ${seedUser.username} already exists, skipping...`);
            }
        }

        console.log('User seeding completed!');
    }
} 