package com.zhengmeng.ocrplatform.document;

import com.zhengmeng.ocrplatform.task.OcrTaskService;
import com.zhengmeng.ocrplatform.task.TaskNotFoundException;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.http.ContentDisposition;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.nio.file.Files;
import java.nio.file.Path;

@RestController
@RequestMapping("/api/v1/ocr/tasks/{taskId}/documents")
public class OcrDocumentController {
    private final OcrTaskService taskService;
    private final OcrDocumentRepository documentRepository;
    private final DocumentStorageService storageService;

    public OcrDocumentController(OcrTaskService taskService,
                                 OcrDocumentRepository documentRepository,
                                 DocumentStorageService storageService) {
        this.taskService = taskService;
        this.documentRepository = documentRepository;
        this.storageService = storageService;
    }

    @GetMapping("/{documentId}/content")
    public ResponseEntity<Resource> getDocumentContent(@PathVariable String taskId, @PathVariable Long documentId) throws Exception {
        taskService.findTask(taskId).orElseThrow(() -> new TaskNotFoundException(taskId));
        OcrDocumentEntity document = documentRepository.findByIdAndTaskId(documentId, taskId)
                .orElseThrow(() -> new TaskNotFoundException(taskId + "/documents/" + documentId));
        Path path = storageService.resolve(document.getObjectPath());
        if (!Files.exists(path) || !Files.isRegularFile(path)) {
            throw new TaskNotFoundException(taskId + "/documents/" + documentId + "/content");
        }
        String contentType = document.getContentType();
        MediaType mediaType = contentType == null || contentType.isBlank()
                ? MediaType.APPLICATION_OCTET_STREAM
                : MediaType.parseMediaType(contentType);
        return ResponseEntity.ok()
                .contentType(mediaType)
                .header(HttpHeaders.CONTENT_DISPOSITION, ContentDisposition.inline()
                        .filename(document.getOriginalFilename())
                        .build()
                        .toString())
                .body(new FileSystemResource(path));
    }
}
