package com.sino.mci.admin.init;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.sino.mci.admin.entity.PlatformRole;
import com.sino.mci.admin.entity.PlatformUser;
import com.sino.mci.admin.entity.Tenant;
import com.sino.mci.admin.entity.UserRole;
import com.sino.mci.admin.repository.PlatformRoleMapper;
import com.sino.mci.admin.repository.PlatformUserMapper;
import com.sino.mci.admin.repository.TenantMapper;
import com.sino.mci.admin.repository.UserRoleMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.CommandLineRunner;
import org.springframework.security.crypto.bcrypt.BCrypt;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

@Slf4j
@Component
@RequiredArgsConstructor
public class DataInitializer implements CommandLineRunner {

    private static final String DEFAULT_TENANT_CODE = "system";
    private static final String DEFAULT_TENANT_NAME = "系统默认租户";
    private static final String GLOBAL_ADMIN_USERNAME = "superadmin";
    private static final String GLOBAL_ADMIN_PASSWORD = "admin123";
    private static final String GLOBAL_ADMIN_ROLE_CODE = "platform_admin";
    private static final String TENANT_ADMIN_ROLE_CODE = "tenant_admin";

    private final TenantMapper tenantMapper;
    private final PlatformUserMapper userMapper;
    private final PlatformRoleMapper roleMapper;
    private final UserRoleMapper userRoleMapper;

    @Override
    @Transactional
    public void run(String... args) {
        initDefaultTenant();
        initPlatformAdminRole();
        initTenantAdminRole();
        initGlobalAdmin();
    }

    private void initDefaultTenant() {
        Tenant existing = tenantMapper.selectOne(
                new LambdaQueryWrapper<Tenant>().eq(Tenant::getTenantCode, DEFAULT_TENANT_CODE));
        if (existing != null) {
            return;
        }
        Tenant tenant = new Tenant();
        tenant.setTenantCode(DEFAULT_TENANT_CODE);
        tenant.setTenantName(DEFAULT_TENANT_NAME);
        tenant.setStatus(1);
        tenantMapper.insert(tenant);
        log.info("已创建默认租户: {}", DEFAULT_TENANT_CODE);
    }

    private void initPlatformAdminRole() {
        PlatformRole existing = roleMapper.selectOne(
                new LambdaQueryWrapper<PlatformRole>().eq(PlatformRole::getRoleCode, GLOBAL_ADMIN_ROLE_CODE));
        if (existing != null) {
            return;
        }
        PlatformRole role = new PlatformRole();
        role.setRoleCode(GLOBAL_ADMIN_ROLE_CODE);
        role.setRoleName("平台管理员");
        role.setPermissions("[\"tenant:manage\", \"user:manage\", \"*\"]");
        role.setStatus(1);
        roleMapper.insert(role);
        log.info("已创建平台管理员角色: {}", GLOBAL_ADMIN_ROLE_CODE);
    }

    private void initTenantAdminRole() {
        PlatformRole existing = roleMapper.selectOne(
                new LambdaQueryWrapper<PlatformRole>().eq(PlatformRole::getRoleCode, TENANT_ADMIN_ROLE_CODE));
        if (existing != null) {
            return;
        }
        PlatformRole role = new PlatformRole();
        role.setRoleCode(TENANT_ADMIN_ROLE_CODE);
        role.setRoleName("租户管理员");
        role.setPermissions("[\"user:manage\", \"tenant:view\"]");
        role.setStatus(1);
        roleMapper.insert(role);
        log.info("已创建租户管理员角色: {}", TENANT_ADMIN_ROLE_CODE);
    }

    private void initGlobalAdmin() {
        PlatformUser existing = userMapper.selectOne(
                new LambdaQueryWrapper<PlatformUser>()
                        .eq(PlatformUser::getTenantCode, DEFAULT_TENANT_CODE)
                        .eq(PlatformUser::getUsername, GLOBAL_ADMIN_USERNAME));
        if (existing != null) {
            return;
        }

        PlatformUser user = new PlatformUser();
        user.setTenantCode(DEFAULT_TENANT_CODE);
        user.setUsername(GLOBAL_ADMIN_USERNAME);
        user.setPassword(BCrypt.hashpw(GLOBAL_ADMIN_PASSWORD, BCrypt.gensalt()));
        user.setRealName("平台管理员");
        user.setStatus(1);
        userMapper.insert(user);

        PlatformRole role = roleMapper.selectOne(
                new LambdaQueryWrapper<PlatformRole>().eq(PlatformRole::getRoleCode, GLOBAL_ADMIN_ROLE_CODE));
        if (role != null) {
            UserRole userRole = new UserRole();
            userRole.setUserId(user.getId());
            userRole.setRoleId(role.getId());
            userRoleMapper.insert(userRole);
        }

        log.info("已创建全局管理员: {}/{}", DEFAULT_TENANT_CODE, GLOBAL_ADMIN_USERNAME);
    }
}
