package com.cfdeployer.model;

import lombok.Data;

import java.nio.file.Path;
import java.time.LocalDateTime;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Data
public class UploadSession {

    private String sessionId;
    private String requestJson;
    private Path workingDirectory;
    private LocalDateTime createdAt;
    private LocalDateTime lastAccessedAt;

    // File type -> chunk tracking
    private Map<String, FileUploadState> fileStates;

    public UploadSession(String sessionId, String requestJson, Path workingDirectory) {
        this.sessionId = sessionId;
        this.requestJson = requestJson;
        this.workingDirectory = workingDirectory;
        this.createdAt = LocalDateTime.now();
        this.lastAccessedAt = LocalDateTime.now();
        this.fileStates = new ConcurrentHashMap<>();
    }

    public void updateLastAccessed() {
        this.lastAccessedAt = LocalDateTime.now();
    }

    @Data
    public static class FileUploadState {
        private String fileName;
        private int totalChunks;
        private Map<Integer, Boolean> receivedChunks;
        private Path targetPath;

        public FileUploadState(String fileName, int totalChunks, Path targetPath) {
            this.fileName = fileName;
            this.totalChunks = totalChunks;
            this.targetPath = targetPath;
            this.receivedChunks = new ConcurrentHashMap<>();
        }

        public void markChunkReceived(int chunkIndex) {
            receivedChunks.put(chunkIndex, true);
        }

        public boolean isComplete() {
            return receivedChunks.size() == totalChunks;
        }

        public int getReceivedChunkCount() {
            return receivedChunks.size();
        }
    }
}
