package cn.reghao.tnb.file.app.zdisk.service;

import cn.reghao.tnb.common.auth.UserContext;
import cn.reghao.tnb.file.app.zdisk.model.dto.SyncedFile;
import cn.reghao.tnb.file.app.zdisk.model.dto.UploadedFile;
import cn.reghao.tnb.file.app.zdisk.model.po.DiskFile;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.io.File;

/**
 * @author reghao
 * @date 2025-09-01 11:46:01
 */
@Slf4j
@Service
public class DiskSyncService {
    private final DiskFolderService diskFolderService;
    private final DiskFileService diskFileService;

    public DiskSyncService(DiskFolderService diskFolderService, DiskFileService diskFileService) {
        this.diskFolderService = diskFolderService;
        this.diskFileService = diskFileService;
    }

    public synchronized void putFile(SyncedFile syncedFile) {
        File file = new File(syncedFile.getPath());
        String path = file.getAbsolutePath();
        File parentFile = file.getParentFile();

        DiskFile diskFile = diskFileService.findByPath(path);
        if (diskFile != null) {
            log.error("DiskFile {} exist", path);
            return;
        }

        String parentPath = parentFile.getAbsolutePath();
        long loginUser = UserContext.getUserId();
        String pid = diskFolderService.createFolders(parentPath, loginUser);
        int channelCode = syncedFile.getChannelCode();
        String uploadId = syncedFile.getUploadId();
        UploadedFile uploadedFile = new UploadedFile(channelCode, uploadId, pid);
        diskFileService.addDiskFile(uploadedFile);
    }
}
