package com.neuroair;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ResourceLoader;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@CrossOrigin
@RestController
@RequestMapping("/api")
public class FileUploadController {

    private static final long MAX_FILE_SIZE = 50 * 1024 * 1024; // 50MB
    private static final String UPLOAD_DIR = "uploads/";

    @PostMapping("/upload")
    public ResponseEntity<List<Map<String, String>>> handleFileUpload(@RequestParam("files") MultipartFile[] files) {
        List<Map<String, String>> responses = new ArrayList<>();

        for (MultipartFile file : files) {
            Map<String, String> response = new HashMap<>();

            if (file.isEmpty()) {
                response.put("success", "false");
                response.put("message", "File is empty");
                responses.add(response);
                continue;
            }

            if (file.getSize() > MAX_FILE_SIZE) {
                response.put("success", "false");
                response.put("message", "File is too large");
                responses.add(response);
                continue;
            }

            try {
                // Получаем абсолютный путь к директории для загрузки
                Path uploadPath = Paths.get(UPLOAD_DIR).toAbsolutePath().normalize();
                Files.createDirectories(uploadPath);

                // Сохранение файла
                Path filePath = uploadPath.resolve(file.getOriginalFilename());
                Files.copy(file.getInputStream(), filePath);

                // Успешное сохранение файла
                response.put("success", "true");
                response.put("filePath", filePath.toString()); // Возврат пути файла
                responses.add(response);
            } catch (IOException e) {
                e.printStackTrace(); // Печать стека исключения для отладки
                response.put("success", "false");
                response.put("message", "File upload failed: " + e.getMessage());
                responses.add(response);
            }
        }

        return ResponseEntity.ok(responses);
    }
}
