package com.qqchen.deploy.backend.deploy.converter;

import com.qqchen.deploy.backend.deploy.dto.FileUploadResultDTO;
import com.qqchen.deploy.backend.deploy.dto.RemoteFileInfoDTO;
import com.qqchen.deploy.backend.framework.ssh.file.SSHFileInfo;
import com.qqchen.deploy.backend.framework.utils.FileUtils;
import org.mapstruct.Mapper;
import org.mapstruct.Mapping;
import org.mapstruct.Named;

import java.util.Date;

/**
 * 远程文件信息转换器（使用MapStruct）
 */
@Mapper(componentModel = "spring")
public interface RemoteFileInfoConverter {
    
    @Mapping(target = "sizeFormatted", source = "size", qualifiedByName = "formatFileSize")
    @Mapping(target = "permissionsOctal", source = "permissionMask", qualifiedByName = "formatPermissionsOctal")
    @Mapping(target = "owner", source = "ownerUid", qualifiedByName = "formatOwner")
    @Mapping(target = "group", source = "groupGid", qualifiedByName = "formatGroup")
    @Mapping(target = "permissions", source = "permissionString")
    RemoteFileInfoDTO toDTO(SSHFileInfo fileInfo);
    
    /**
     * 转换SSHFileInfo为上传结果DTO
     */
    default FileUploadResultDTO toUploadResultDTO(SSHFileInfo fileInfo) {
        return FileUploadResultDTO.builder()
            .fileName(fileInfo.getName())
            .remotePath(fileInfo.getPath())
            .fileSize(fileInfo.getSize())
            .fileSizeFormatted(formatFileSize(fileInfo.getSize()))
            .uploadTime(new Date())
            .permissions(fileInfo.getPermissionString())
            .success(true)
            .build();
    }
    
    /**
     * 格式化文件大小
     */
    @Named("formatFileSize")
    default String formatFileSize(Long size) {
        return FileUtils.formatFileSize(size);
    }
    
    /**
     * 格式化权限为八进制字符串
     */
    @Named("formatPermissionsOctal")
    default String formatPermissionsOctal(Integer permissionMask) {
        if (permissionMask == null) {
            return null;
        }
        return String.format("0%o", permissionMask);
    }
    
    /**
     * 格式化所有者信息
     */
    @Named("formatOwner")
    default String formatOwner(Integer uid) {
        if (uid == null) {
            return null;
        }
        // TODO: 未来可以通过执行 getent passwd 命令获取用户名
        // 目前只返回 UID 的格式
        return "(" + uid + ")";
    }
    
    /**
     * 格式化组信息
     */
    @Named("formatGroup")
    default String formatGroup(Integer gid) {
        if (gid == null) {
            return null;
        }
        // TODO: 未来可以通过执行 getent group 命令获取组名
        // 目前只返回 GID 的格式
        return "(" + gid + ")";
    }
}
