package com.ycwl.basic.image.pipeline.stages;

import com.ycwl.basic.image.pipeline.core.PhotoProcessContext;
import com.ycwl.basic.pipeline.annotation.StageConfig;
import com.ycwl.basic.pipeline.core.AbstractPipelineStage;
import com.ycwl.basic.pipeline.core.StageResult;
import com.ycwl.basic.pipeline.enums.StageOptionalMode;
import com.ycwl.basic.service.pc.SourceService;
import lombok.extern.slf4j.Slf4j;

import java.io.File;

/**
 * 源图片上传和更新Stage
 * 专门用于将增强后的图片上传并更新数据库中的URL
 *
 * 与UploadStage的区别:
 * - UploadStage: 通用上传,仅上传到存储并设置Context.resultUrl
 * - SourcePhotoUpdateStage: 专门用于源图片,上传+更新数据库source表的URL字段
 */
@Slf4j
@StageConfig(
    stageId = "source_photo_update",
    optionalMode = StageOptionalMode.UNSUPPORT,
    description = "源图片上传和数据库更新",
    defaultEnabled = true
)
public class SourcePhotoUpdateStage extends AbstractPipelineStage<PhotoProcessContext> {

    private final SourceService sourceService;
    private final Long sourceId;

    /**
     * 构造函数
     *
     * @param sourceService 源图片服务
     * @param sourceId 源图片ID
     */
    public SourcePhotoUpdateStage(SourceService sourceService, Long sourceId) {
        this.sourceService = sourceService;
        this.sourceId = sourceId;
    }

    @Override
    public String getName() {
        return "SourcePhotoUpdateStage";
    }

    @Override
    protected StageResult<PhotoProcessContext> doExecute(PhotoProcessContext context) {
        File fileToUpload = context.getCurrentFile();
        if (fileToUpload == null || !fileToUpload.exists()) {
            return StageResult.failed("没有可上传的文件");
        }

        if (sourceService == null) {
            return StageResult.failed("SourceService未注入");
        }

        if (sourceId == null) {
            return StageResult.failed("SourceId为空");
        }

        try {

            // 调用SourceService上传并更新URL
            String uploadedUrl = sourceService.uploadAndUpdateUrl(sourceId, fileToUpload);

            // 设置结果URL到Context
            context.setResultUrl(uploadedUrl);

            log.info("源图片上传并更新成功: sourceId={}, url={}", sourceId, uploadedUrl);

            return StageResult.success("已上传并更新: " + uploadedUrl);

        } catch (Exception e) {
            log.error("源图片上传并更新失败: sourceId={}", sourceId, e);
            return StageResult.failed("上传并更新失败: " + e.getMessage(), e);
        }
    }

}
