package org.cmh.backend.authentication.service;

import jakarta.annotation.PostConstruct;
import lombok.Getter;
import org.cmh.backend.authentication.dto.VerificationCodeResponse;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.stream.Stream;

@Service
public class VerificationCodeService {

    @Value("${verification.code.images.path}")
    private String verificationCodeImagesPath;

    @Getter
    private List<String> verificationCodeList = new ArrayList<>();

    @PostConstruct
    public void init() {
        loadVerificationCodeImages();
    }

    private void loadVerificationCodeImages() {
        try (Stream<Path> paths = Files.list(Paths.get(verificationCodeImagesPath))) {
            paths.filter(path -> path.toString().endsWith(".png"))
                    .forEach(path -> verificationCodeList.add(path.getFileName().toString()));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public VerificationCodeResponse provideVerificationCode() {
        if (verificationCodeList.isEmpty()) {
            return null;
        }
        Random random = new Random();
        int code = random.nextInt(random.nextInt(verificationCodeList.size()));
        String selectedCode = verificationCodeList.get(code);
        return new VerificationCodeResponse(selectedCode.split("\\.")[0], "/verificationCodeImages/" + selectedCode);
    }

}