package com.storycove.controller;

import com.storycove.service.ImageService;
import com.storycove.service.LibraryService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import jakarta.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api/files")
public class FileController {
    private static final Logger log = LoggerFactory.getLogger(FileController.class);
    
    private final ImageService imageService;
    private final LibraryService libraryService;
    
    public FileController(ImageService imageService, LibraryService libraryService) {
        this.imageService = imageService;
        this.libraryService = libraryService;
    }
    
    private String getCurrentLibraryId() {
        String libraryId = libraryService.getCurrentLibraryId();
        log.debug("FileController - Current Library ID: {}", libraryId);
        return libraryId != null ? libraryId : "default";
    }
    
    @PostMapping("/upload/cover")
    public ResponseEntity<?> uploadCover(@RequestParam("file") MultipartFile file) {
        try {
            String imagePath = imageService.uploadImage(file, ImageService.ImageType.COVER);
            
            Map<String, String> response = new HashMap<>();
            response.put("message", "Cover uploaded successfully");
            response.put("path", imagePath);
            String currentLibraryId = getCurrentLibraryId();
            String imageUrl = "/api/files/images/" + currentLibraryId + "/" + imagePath;
            response.put("url", imageUrl);
            
            log.debug("Upload response - path: {}, url: {}", imagePath, imageUrl);
            
            return ResponseEntity.ok(response);
        } catch (IllegalArgumentException e) {
            return ResponseEntity.badRequest().body(Map.of("error", e.getMessage()));
        } catch (IOException e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(Map.of("error", "Failed to upload image: " + e.getMessage()));
        }
    }
    
    @PostMapping("/upload/avatar")
    public ResponseEntity<?> uploadAvatar(@RequestParam("file") MultipartFile file) {
        try {
            String imagePath = imageService.uploadImage(file, ImageService.ImageType.AVATAR);
            
            Map<String, String> response = new HashMap<>();
            response.put("message", "Avatar uploaded successfully");
            response.put("path", imagePath);
            String currentLibraryId = getCurrentLibraryId();
            response.put("url", "/api/files/images/" + currentLibraryId + "/" + imagePath);
            
            return ResponseEntity.ok(response);
        } catch (IllegalArgumentException e) {
            return ResponseEntity.badRequest().body(Map.of("error", e.getMessage()));
        } catch (IOException e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(Map.of("error", "Failed to upload image: " + e.getMessage()));
        }
    }
    
    @GetMapping("/images/{libraryId}/**")
    public ResponseEntity<Resource> serveImage(@PathVariable String libraryId, HttpServletRequest request) {
        try {
            // Extract the full request path after /api/files/images/{libraryId}/
            String requestURI = request.getRequestURI();
            String imagePath = requestURI.replaceFirst(".*/api/files/images/" + libraryId + "/", "");
            
            if (!imageService.imageExistsInLibrary(imagePath, libraryId)) {
                return ResponseEntity.notFound().build();
            }
            
            Path fullPath = imageService.getImagePathInLibrary(imagePath, libraryId);
            Resource resource = new FileSystemResource(fullPath);
            
            if (!resource.exists()) {
                return ResponseEntity.notFound().build();
            }
            
            // Determine content type
            String contentType = Files.probeContentType(fullPath);
            if (contentType == null) {
                contentType = "application/octet-stream";
            }
            
            return ResponseEntity.ok()
                    .contentType(MediaType.parseMediaType(contentType))
                    .header(HttpHeaders.CACHE_CONTROL, "public, max-age=31536000") // Cache for 1 year
                    .body(resource);
                    
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }
    
    @DeleteMapping("/images")
    public ResponseEntity<?> deleteImage(@RequestParam String path) {
        try {
            boolean deleted = imageService.deleteImage(path);
            
            if (deleted) {
                return ResponseEntity.ok(Map.of("message", "Image deleted successfully"));
            } else {
                return ResponseEntity.notFound().build();
            }
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(Map.of("error", "Failed to delete image: " + e.getMessage()));
        }
    }
}