package com.yaoai;

import cn.hutool.crypto.digest.BCrypt;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.yaoai.billing.service.BillingService;
import com.yaoai.domain.entity.Tenant;
import com.yaoai.domain.entity.TenantMember;
import com.yaoai.domain.entity.User;
import com.yaoai.domain.mapper.TenantMapper;
import com.yaoai.domain.mapper.TenantMemberMapper;
import com.yaoai.domain.mapper.UserMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;

/** 仅 local profile 启动时执行，幂等 */
@Slf4j
@Component
@Profile("local")
@RequiredArgsConstructor
public class DevDataInitializer implements ApplicationRunner {

    private static final String ADMIN_EMAIL = "admin@yaoai.com";
    private static final String ADMIN_PASSWORD = "Admin@123";

    private final UserMapper userMapper;
    private final TenantMapper tenantMapper;
    private final TenantMemberMapper tenantMemberMapper;
    private final BillingService billingService;

    @Override
    @Transactional
    public void run(ApplicationArguments args) {
        boolean exists = userMapper.selectCount(
                Wrappers.<User>lambdaQuery()
                        .eq(User::getEmail, ADMIN_EMAIL)
                        .isNull(User::getDeletedAt)) > 0;
        if (exists) {
            return;
        }
        log.info(">>> 初始化开发环境管理员账号...");

        Tenant tenant = new Tenant();
        tenant.setName("YaoAI 默认租户");
        tenant.setSlug("yaoai-default");
        tenant.setPlan("pro");
        tenant.setStatus(1);
        tenant.setCredits(BigDecimal.valueOf(10000));
        tenant.setFrozenCredits(BigDecimal.ZERO);
        tenantMapper.insert(tenant);

        User admin = new User();
        admin.setTenantId(tenant.getId());
        admin.setUsername("admin");
        admin.setEmail(ADMIN_EMAIL);
        admin.setPasswordHash(BCrypt.hashpw(ADMIN_PASSWORD, BCrypt.gensalt()));
        admin.setRole("admin");
        admin.setStatus(1);
        userMapper.insert(admin);

        TenantMember member = new TenantMember();
        member.setTenantId(tenant.getId());
        member.setUserId(admin.getId());
        member.setRole("owner");
        tenantMemberMapper.insert(member);

        billingService.initBalance(tenant.getId(), BigDecimal.valueOf(10000));
        log.info(">>> 管理员创建成功: email={}, password={}", ADMIN_EMAIL, ADMIN_PASSWORD);
    }
}
