package com.devjob.config;

import com.devjob.domain.Member;
import com.devjob.domain.Role;
import com.devjob.repository.MemberRepository;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.event.EventListener;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;

/**
 * EP25: 애플리케이션 시작 시 관리자(ADMIN) 계정이 없으면 하나 생성한다.
 * - 운영 환경에서는 비밀번호를 환경 변수로 분리해야 하지만, 포트폴리오에서는 학습 목적상 하드코딩한다.
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class AdminAccountInitializer {

    private static final String ADMIN_EMAIL = "admin@devjob.com";
    private static final String ADMIN_PASSWORD = "admin1234!";

    private final MemberRepository memberRepository;
    private final PasswordEncoder passwordEncoder;

    @EventListener(ApplicationReadyEvent.class)
    public void initAdminAccount() {
        if (memberRepository.existsByEmail(ADMIN_EMAIL)) {
            return;
        }

        Member admin = Member.builder()
                .email(ADMIN_EMAIL)
                .password(passwordEncoder.encode(ADMIN_PASSWORD))
                .role(Role.ADMIN)
                .build();

        memberRepository.save(admin);
        log.info("관리자 계정이 생성되었습니다: {}", ADMIN_EMAIL);
    }
}
