package com.erp.provisioning;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

/**
 * 신규 회사 DB 에 {prefix}_admin (COMPANY_ADMIN) 계정을 생성.
 * BCrypt 해시만 저장되며, 초기 비밀번호는 호출자가 생성/전달.
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class AdminAccountCreator {

    private final PasswordEncoder passwordEncoder;

    /**
     * @param dst                신규 회사 DB 커넥션 (autoCommit 무관, 호출자가 트랜잭션 관리)
     * @param companyCode        COMPANY_MNG.company_code (FK 성격)
     * @param userId             예: qnc_admin
     * @param rawPassword        평문 비밀번호 (BCrypt 해시 후 저장됨)
     * @param userName           표시 이름
     * @param forcePasswordChange true 면 첫 로그인 시 비밀번호 변경을 강제 (RUN_082)
     */
    public void createCompanyAdmin(Connection dst, String companyCode, String userId,
                                   String rawPassword, String userName,
                                   boolean forcePasswordChange) throws SQLException {
        String hash = passwordEncoder.encode(rawPassword);
        String sql = "INSERT INTO user_info " +
                "(user_id, user_password, user_name, company_code, user_type, status, force_password_change, created_date) " +
                "VALUES (?, ?, ?, ?, 'COMPANY_ADMIN', 'active', ?, NOW())";
        try (PreparedStatement ps = dst.prepareStatement(sql)) {
            ps.setString(1, userId);
            ps.setString(2, hash);
            ps.setString(3, userName);
            ps.setString(4, companyCode);
            ps.setBoolean(5, forcePasswordChange);
            int affected = ps.executeUpdate();
            log.info("[Provisioning] CREATE ADMIN: {} (company={}, rows={}, force_pw_change={})",
                    userId, companyCode, affected, forcePasswordChange);
        }
    }
}
