package com.njcn.rdms.module.system.dal.mysql.file;

import com.njcn.rdms.framework.common.pojo.PageResult;
import com.njcn.rdms.framework.mybatis.core.mapper.BaseMapperX;
import com.njcn.rdms.framework.mybatis.core.query.LambdaQueryWrapperX;
import com.njcn.rdms.module.system.controller.admin.file.vo.file.FilePageReqVO;
import com.njcn.rdms.module.system.dal.dataobject.file.FileDO;
import org.apache.ibatis.annotations.Mapper;

import java.util.Objects;

import static com.njcn.rdms.framework.common.util.http.HttpUtils.removeUrlQuery;

/**
 * 文件操作 Mapper
 *
 * @author hongawen
 */
@Mapper
public interface FileMapper extends BaseMapperX<FileDO> {

    default PageResult<FileDO> selectPage(FilePageReqVO reqVO) {
        return selectPage(reqVO, new LambdaQueryWrapperX<FileDO>()
                .likeIfPresent(FileDO::getPath, reqVO.getPath())
                .likeIfPresent(FileDO::getType, reqVO.getType())
                .betweenIfPresent(FileDO::getCreateTime, reqVO.getCreateTime())
                .orderByDesc(FileDO::getId));
    }

    default FileDO selectByUrl(String url) {
        FileDO file = selectFirstOne(FileDO::getUrl, url);
        String urlWithoutQuery = removeUrlQuery(url);
        if (file == null && !Objects.equals(urlWithoutQuery, url)) {
            file = selectOne(new LambdaQueryWrapperX<FileDO>()
                    .likeRight(FileDO::getUrl, urlWithoutQuery)
                    .last("LIMIT 1"));
        }
        if (file == null && !Objects.equals(urlWithoutQuery, url)) {
            file = selectFirstOne(FileDO::getUrl, urlWithoutQuery);
        }
        return file;
    }

    /**
     * 按 (configId, path) 查询文件记录
     *
     * 用于匿名图片代理接口 {@code GET /system/file/{configId}/get/**} 的存在性校验：
     * 当 infra_file 已被逻辑删除时，MyBatis-Plus 全局过滤会自动加上 deleted=0，
     * 这里查不到即视为已删除，由调用方返 404 给浏览器（裂图），避免外部探测到对象存储仍可读
     */
    default FileDO selectByConfigIdAndPath(Long configId, String path) {
        return selectOne(new LambdaQueryWrapperX<FileDO>()
                .eq(FileDO::getConfigId, configId)
                .eq(FileDO::getPath, path)
                .last("LIMIT 1"));
    }

}
