package com.snack.server.module.file.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.snack.server.exception.BusinessException;
import com.snack.server.common.storage.FileStorage;
import com.snack.server.common.storage.FileStoreResult;
import com.snack.server.module.file.entity.UploadFile;
import com.snack.server.module.file.enums.FileBizTypeEnum;
import com.snack.server.module.file.mapper.UploadFileMapper;
import com.snack.server.module.file.service.FileService;
import com.snack.server.module.file.vo.FileUploadVO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;

/**
 * 文件上传业务实现
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class FileServiceImpl implements FileService {

    /** 允许的图片类型 */
    private static final List<String> IMAGE_EXTS =
            Arrays.asList("jpg", "jpeg", "png", "gif", "webp");

    private final FileStorage fileStorage;
    private final UploadFileMapper uploadFileMapper;

    @Override
    public FileUploadVO upload(MultipartFile file, String bizType) {
        return uploadWithUploader(file, bizType, null);
    }

    @Override
    public FileUploadVO uploadWithUploader(MultipartFile file, String bizType, Long uploaderId) {
        if (file == null || file.isEmpty()) {
            throw new BusinessException(1050, "文件为空");
        }
        String originalName = file.getOriginalFilename();
        if (StrUtil.isBlank(originalName)) {
            originalName = "unknown";
        }
        String ext = StrUtil.subAfter(originalName, '.', true);
        if (StrUtil.isBlank(ext)) {
            throw new BusinessException(1051, "无法识别文件类型");
        }
        ext = ext.toLowerCase();

        // 图片类型校验
        FileBizTypeEnum biz = resolveBizType(bizType);
        if (biz == FileBizTypeEnum.AVATAR || biz == FileBizTypeEnum.ADMIN_AVATAR
                || biz == FileBizTypeEnum.PRODUCT || biz == FileBizTypeEnum.SKU
                || biz == FileBizTypeEnum.BANNER || biz == FileBizTypeEnum.NOTICE
                || biz == FileBizTypeEnum.CATEGORY) {
            if (!IMAGE_EXTS.contains(ext)) {
                throw new BusinessException(1051, "仅支持图片格式：" + IMAGE_EXTS);
            }
        }

        // 1. 存物理文件
        byte[] bytes;
        try {
            bytes = file.getBytes();
        } catch (IOException e) {
            log.error("读取上传文件失败", e);
            throw new BusinessException(1050, "读取文件失败");
        }
        FileStoreResult store = fileStorage.store(bytes, originalName, biz.getCode());

        // 2. 写数据库
        UploadFile entity = new UploadFile();
        entity.setName(originalName);
        entity.setPath(store.getPath());
        entity.setUrl(store.getUrl());
        entity.setSize(store.getSize());
        entity.setContentType(store.getContentType());
        entity.setStorageType("local");
        entity.setBizType(biz.getCode());
        entity.setUploadBy(uploaderId);
        uploadFileMapper.insert(entity);

        // 3. 返回
        FileUploadVO vo = new FileUploadVO();
        BeanUtil.copyProperties(entity, vo);
        log.info("文件上传成功 id={} bizType={} url={}", entity.getId(), biz, store.getUrl());
        return vo;
    }

    @Override
    public void deleteFile(Long id) {
        UploadFile entity = uploadFileMapper.selectById(id);
        if (entity == null) {
            throw new BusinessException(1050, "文件不存在");
        }
        fileStorage.delete(entity.getPath());
        uploadFileMapper.deleteById(id);
        log.info("删除文件 id={} path={}", id, entity.getPath());
    }

    @Override
    public void deleteByPath(String path) {
        if (StrUtil.isBlank(path)) return;
        // 如果是完整 URL，先反查成 path
        if (path.startsWith("http://") || path.startsWith("https://")) {
            path = fileStorage.parsePathFromUrl(path);
            if (path == null) {
                log.warn("URL 反查 path 失败：{}", path);
                return;
            }
        }
        fileStorage.delete(path);
        uploadFileMapper.delete(
                new com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<UploadFile>()
                        .eq(UploadFile::getPath, path)
        );
    }

    @Override
    public UploadFile getById(Long id) {
        return uploadFileMapper.selectById(id);
    }

    @Override
    public FileBizTypeEnum resolveBizType(String bizType) {
        return FileBizTypeEnum.of(bizType);
    }
}
