package de.avatic.taricdb.web.setup;

import java.io.IOException;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Profile;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import de.avatic.taricdb.model.SetupStatus;
import de.avatic.taricdb.service.SetupService;
import de.avatic.taricdb.service.SetupStatusService;

@RestController
@Profile("setup")
public class SetupRestController {
	
	@Autowired
	private SetupService setupService;
	
	@Autowired
	private SetupStatusService setupStatusService;

	@PostMapping("/setup/upload")
    public ResponseEntity<String> uploadFile(@RequestParam MultipartFile file) {
				
        if (file.isEmpty() || !file.getOriginalFilename().endsWith(".zip")) {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Invalid file. Please upload a ZIP file.");
        }
        
        try {
    		setupStatusService.resetOnStartup();
			setupService.run(file.getBytes());
		} catch (IOException e) {
			e.printStackTrace();
		}
        
        return ResponseEntity.ok("File uploaded successfully: " + file.getOriginalFilename());
    }
	
	@GetMapping("/setup/status")
	public ResponseEntity<SetupStatus> getStatus() {		
		return ResponseEntity.ok(setupStatusService.getLatestStatus());
	}
	
}
