//
// Created by Administrator on 2026/4/27.
//

#ifndef RTTHREAD_HEAD_FILE_SERVICE_IMPL_H
#define RTTHREAD_HEAD_FILE_SERVICE_IMPL_H


#include <string>

#include "erpc/proto/generated/file_service_server.hpp"
#include <rtthread.h>


class FileServiceImpl : public erpcShim::file_service_interface
{
public:
    FileServiceImpl();
    ~FileServiceImpl() override;

    int32_t fileWriteBegin(const char* path, uint32_t total_size) override;
    int32_t fileWriteChunk(const binary_t* data) override;
    int32_t fileWriteEnd(void) override;
    int32_t fileWriteAbort(void) override;

private:
    // 当前实现一次只允许一个上传会话；下面的上传状态由 upload_mutex_ 保护。
    rt_mutex_t upload_mutex_;
    int upload_fd_;
    uint32_t upload_expected_size_;
    uint32_t upload_received_size_;
    std::string upload_target_path_;
    std::string upload_temp_path_;

    // 规范化上传路径，并拒绝设备路径和父目录跳转。
    static bool normalizeUploadPath(const char* path, std::string* normalized);
    static int32_t posixErrorToRtError(void);
    void resetUploadStateLocked(void);
    // 调用方必须已经持有 upload_mutex_。
    int32_t abortUploadLocked(void);
};

#endif
