package com.example.bricklog.controller;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

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

import com.example.bricklog.model.LegoBuild;
import com.example.bricklog.repository.LegoBuildRepository;

@RestController
@RequestMapping("/api/builds")
public class LegoBuildController {

    private static final String IMAGE_DIRECTORY = "uploads/images/";

    @Autowired
    private LegoBuildRepository legoBuildRepository;

    @PostMapping("/add")
    public ResponseEntity<?> addLegoBuild(
            @RequestParam("name") String name,
            @RequestParam("builder") String builder,
            @RequestParam("isKitset") boolean isKitset,
            @RequestParam("description") String description,
            @RequestParam("image") MultipartFile image) {

        // Save the image file
        String filePath = saveImageFile(image);

        // Save the LegoBuild with image path
        LegoBuild legoBuild = new LegoBuild(name, builder, isKitset, description);
        legoBuild.setImagePath(filePath);
        legoBuildRepository.save(legoBuild);

        return new ResponseEntity<>("Build added successfully with image.", HttpStatus.OK);
    }

    private String saveImageFile(MultipartFile image) {
        try {
            Path directoryPath = Paths.get(IMAGE_DIRECTORY);
            if (!Files.exists(directoryPath)) {
                Files.createDirectories(directoryPath); // Create directory if it doesn’t exist
            }
            String filePath = IMAGE_DIRECTORY + image.getOriginalFilename();
            File file = new File(filePath);
            image.transferTo(file);  // Save the image
            return filePath;
        } catch (IOException e) {
            throw new RuntimeException("Failed to store image file", e);
        }
    }
}
