package com.ruoyi.info.collection.service.support;

import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.file.FileUploadUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;

/**
 * 征信 HTML 服务器落盘与远程访问地址生成。
 */
@Component
public class CreditHtmlStorageService {

    private static final String CREDIT_HTML_DIR = "credit-html";
    private static final String[] HTML_EXTENSIONS = {"html", "htm"};

    @Value("${credit-parse.api.file-public-base-url}")
    private String filePublicBaseUrl;

    public StoredCreditHtml save(MultipartFile file) throws Exception {
        String profilePath = FileUploadUtils.upload(getCreditHtmlBaseDir(), file, HTML_EXTENSIONS);
        return new StoredCreditHtml(profilePath, buildRemotePath(profilePath));
    }

    private String getCreditHtmlBaseDir() {
        return RuoYiConfig.getProfile() + File.separator + CREDIT_HTML_DIR;
    }

    private String buildRemotePath(String profilePath) {
        if (StringUtils.isBlank(filePublicBaseUrl)) {
            throw new IllegalStateException("征信HTML公开访问地址未配置");
        }
        String normalizedBaseUrl = StringUtils.stripEnd(filePublicBaseUrl.trim(), "/");
        String normalizedProfilePath = profilePath.startsWith("/") ? profilePath : "/" + profilePath;
        return normalizedBaseUrl + normalizedProfilePath;
    }

    public record StoredCreditHtml(String profilePath, String remotePath) {
    }
}
