package ru.ldeloff.hedgehogcloud.config.initclass;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import ru.ldeloff.hedgehogcloud.entity.RoleEntity;
import ru.ldeloff.hedgehogcloud.entity.UserEntity;
import ru.ldeloff.hedgehogcloud.service.RoleService;
import ru.ldeloff.hedgehogcloud.service.UserService;

import java.util.HashSet;
import java.util.List;

@Component
public class InitDB implements ApplicationRunner {
    UserService userService;
    RoleService roleService;

    public InitDB(UserService userService, RoleService roleService) {
        this.userService = userService;
        this.roleService = roleService;
    }

    @Override
    @Transactional
    public void run(ApplicationArguments args) throws Exception {
        RoleEntity role = new RoleEntity();
        role.setName("ROLE_ADMIN");
        roleService.saveRole(role);

        RoleEntity role2 = new RoleEntity();
        role2.setName("ROLE_USER");
        roleService.saveRole(role2);

        UserEntity user = new UserEntity();
        user.setUsername("admin");
        user.setPassword("123");
        user.setRoles(new HashSet<>(List.of(roleService.getByName(role.getName()))));
        userService.saveUser(user);

        UserEntity user2 = new UserEntity();
        user2.setUsername("user");
        user2.setPassword("123");
        user2.setRoles(new HashSet<>(List.of(roleService.getByName(role2.getName()))));
        userService.saveUser(user2);
    }
}
