/**
 * SSH文件管理API服务
 */
import request from '@/utils/request';

const API_BASE = '/api/v1/server-ssh';

export interface RemoteFileInfo {
    name: string;
    path: string;
    isDirectory: boolean;
    size: number | null;
    sizeFormatted: string;
    permissions: string;
    permissionsOctal?: string;
    modifyTime: string;
    owner: string;
    ownerUid?: number;
    group: string;
    groupGid?: number;
    extension: string | null;
    isSymlink: boolean;
    linkTarget: string | null;
}

export interface FileUploadResult {
    fileName: string;
    remotePath: string;
    fileSize: number;
    fileSizeFormatted: string;
    uploadTime: string;
    permissions: string;
    success: boolean;
    errorMessage: string | null;
}

// 异步上传相关类型
export type UploadTaskStatus = 'PENDING' | 'UPLOADING' | 'SUCCESS' | 'FAILED' | 'CANCELLED';

export interface AsyncUploadResponse {
    taskId: string;
    message: string;
}

export interface UploadTaskInfo {
    taskId: string;
    fileName: string;
    fileSize: number;
    fileSizeFormatted: string;
    uploadedSize: number;
    uploadedSizeFormatted: string;
    progress: number;
    status: UploadTaskStatus;
    metadata?: {
        serverId: number;
        remotePath: string;
        overwrite: boolean;
    };
    errorMessage?: string;
    createTime?: string;
    updateTime?: string;
}

export interface UploadProgressMessage {
    taskId: string;
    status: UploadTaskStatus;
    progress: number;
    uploaded: number;
    total: number;
    uploadedFormatted: string;
    totalFormatted: string;
    errorMessage?: string;
    timestamp: number;
}

/**
 * 浏览目录
 */
export const browseDirectory = async (
    serverId: number,
    path?: string
): Promise<RemoteFileInfo[]> => {
    const response = await request.get(`${API_BASE}/${serverId}/files/browse`, {
        params: { path },
    });
    return response; // request拦截器已经提取了data字段
};

/**
 * 创建目录
 */
export const createDirectory = async (
    serverId: number,
    path: string
): Promise<void> => {
    await request.post(`${API_BASE}/${serverId}/files/mkdir`, null, {
        params: { path },
    });
};

/**
 * 删除文件/目录
 */
export const removeFile = async (
    serverId: number,
    path: string,
    recursive?: boolean
): Promise<void> => {
    await request.delete(`${API_BASE}/${serverId}/files/remove`, {
        params: { path, recursive },
    });
};

/**
 * 上传文件（同步，适用于小文件）
 */
export const uploadFile = async (
    serverId: number,
    file: File,
    remotePath: string,
    overwrite?: boolean,
    onProgress?: (progress: number) => void
): Promise<FileUploadResult> => {
    const formData = new FormData();
    formData.append('file', file);
    formData.append('remotePath', remotePath);
    if (overwrite !== undefined) {
        formData.append('overwrite', String(overwrite));
    }

    const response = await request.post(
        `${API_BASE}/${serverId}/files/upload`,
        formData,
        {
            headers: {
                'Content-Type': 'multipart/form-data',
            },
            onUploadProgress: (progressEvent) => {
                if (onProgress && progressEvent.total) {
                    const progress = Math.round(
                        (progressEvent.loaded * 100) / progressEvent.total
                    );
                    onProgress(progress);
                }
            },
        }
    );
    return response; // request拦截器已经提取了data字段
};

/**
 * 提交异步上传任务
 */
export const submitAsyncUpload = async (
    serverId: number,
    file: File,
    remotePath: string,
    overwrite?: boolean
): Promise<AsyncUploadResponse> => {
    const formData = new FormData();
    formData.append('file', file);
    formData.append('remotePath', remotePath);
    if (overwrite !== undefined) {
        formData.append('overwrite', String(overwrite));
    }

    const response = await request.post(
        `${API_BASE}/${serverId}/files/upload-async`,
        formData,
        {
            headers: {
                'Content-Type': 'multipart/form-data',
            },
        }
    );
    return response;
};

/**
 * 查询上传任务状态
 */
export const getUploadTaskStatus = async (
    serverId: number,
    taskId: string
): Promise<UploadTaskInfo> => {
    const response = await request.get(
        `${API_BASE}/${serverId}/files/upload-task/${taskId}`
    );
    return response;
};

/**
 * 取消上传任务
 */
export const cancelUploadTask = async (
    serverId: number,
    taskId: string
): Promise<{ cancelled: boolean }> => {
    const response = await request.delete(
        `${API_BASE}/${serverId}/files/upload-task/${taskId}`
    );
    return response;
};

/**
 * 重命名文件/目录
 */
export const renameFile = async (
    serverId: number,
    oldPath: string,
    newPath: string
): Promise<void> => {
    await request.put(`${API_BASE}/${serverId}/files/rename`, null, {
        params: { oldPath, newPath },
    });
};

/**
 * 路径工具函数
 */
export const pathUtils = {
    /**
     * 拼接路径
     */
    join(basePath: string, fileName: string): string {
        if (!basePath) return fileName;
        return basePath.endsWith('/') 
            ? basePath + fileName 
            : basePath + '/' + fileName;
    },

    /**
     * 获取父路径
     */
    getParent(path: string): string {
        if (!path || path === '/') return '/';
        const lastSlash = path.lastIndexOf('/');
        return lastSlash <= 0 ? '/' : path.substring(0, lastSlash);
    },

    /**
     * 获取文件名
     */
    getFileName(path: string): string {
        const lastSlash = path.lastIndexOf('/');
        return lastSlash === -1 ? path : path.substring(lastSlash + 1);
    },
};
