package cn.reghao.tnb.content.app.vod.service;

import cn.reghao.jutil.jdk.web.result.Result;
import cn.reghao.tnb.common.auth.UserContext;
import cn.reghao.tnb.content.api.constant.VideoErrorType;
import cn.reghao.tnb.content.api.constant.VideoStatus;
import cn.reghao.tnb.content.app.vod.db.mapper.VideoErrorMapper;
import cn.reghao.tnb.content.app.vod.db.mapper.VideoPostMapper;
import cn.reghao.tnb.content.app.vod.model.dto.VideoErrorReport;
import cn.reghao.tnb.content.app.vod.model.po.VideoError;
import cn.reghao.tnb.search.api.iface.DataSearchService;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.stereotype.Service;

import java.util.Set;

/**
 * @author reghao
 * @date 2025-08-02 20:12:44
 */
@Slf4j
@Service
public class VideoEditService {
    @DubboReference(check = false, retries = 0, timeout = 60_000)
    private DataSearchService dataSearchService;

    private final VideoPostMapper videoPostMapper;
    private final VideoErrorMapper videoErrorMapper;
    private final Set<Long> adminUsers = Set.of(10001L, 10002L);

    public VideoEditService(VideoPostMapper videoPostMapper, VideoErrorMapper videoErrorMapper) {
        this.videoPostMapper = videoPostMapper;
        this.videoErrorMapper = videoErrorMapper;
    }

    public Result errorReport(VideoErrorReport videoErrorReport) {
        long loginUser = UserContext.getUserId();
        if (!adminUsers.contains(loginUser)) {
            return Result.fail("no permission");
        }

        String videoId = videoErrorReport.getVideoId();
        int errCode = videoErrorReport.getErrorCode();
        VideoErrorType errorType = VideoErrorType.getDescByCode(errCode);
        int videoStatus;
        switch (errorType) {
            case noCover:
            case noAudio:
            case noVideo:
                videoStatus = VideoStatus.needRepair.getCode();
                break;
            case noResource:
                videoStatus = VideoStatus.revoke.getCode();
                break;
            case hasAd:
                videoStatus = VideoStatus.hasAd.getCode();
                break;
            case needRestore:
                videoStatus = VideoStatus.needRestore.getCode();
                break;
            default:
                return Result.fail("unknown errorType");
        }

        videoPostMapper.updateVideoStatus(videoId, videoStatus);
        if (videoStatus != VideoStatus.revoke.getCode() || videoStatus != VideoStatus.needRestore.getCode()) {
            VideoError videoError = new VideoError(videoErrorReport);
            videoErrorMapper.save(videoError);
        }

        if (videoStatus == VideoStatus.revoke.getCode()) {
            dataSearchService.deleteVideoSummary(videoId);
        }

        return Result.success();
    }
}
