package com.zioinfo.mall.uiws.schedule.controller;

import com.zioinfo.mall.common.ApiResponse;
import com.zioinfo.mall.uiws.schedule.dto.ScheduleDtos.AttachmentDto;
import com.zioinfo.mall.uiws.schedule.service.AttachmentService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
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.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;

/**
 * UIWS 이식 — 첨부파일(모듈 02, 폴리모픽 SCHEDULE/DIARY). 인증 필수(/api/attachments).
 */
@Tag(name = "UIWS-첨부", description = "UIWS 이식: 일정/일지 첨부파일")
@RestController
@RequestMapping("/api/attachments")
@RequiredArgsConstructor
public class AttachmentController {

    private final AttachmentService attachmentService;

    @Operation(summary = "첨부파일 업로드(일정/일지)")
    @PostMapping
    public ApiResponse<AttachmentDto> upload(
            @RequestParam("refType") String refType,
            @RequestParam("refId") Long refId,
            @RequestParam("file") MultipartFile file) {
        return ApiResponse.ok(attachmentService.upload(refType, refId, file));
    }

    @Operation(summary = "첨부 다운로드")
    @GetMapping("/{id}/download")
    public ResponseEntity<Resource> download(@PathVariable("id") Long id) {
        AttachmentService.DownloadFile f = attachmentService.download(id);
        Resource resource = new FileSystemResource(f.path());
        String contentType;
        try {
            contentType = Files.probeContentType(f.path());
        } catch (IOException e) {
            contentType = null;
        }
        ContentDisposition cd = ContentDisposition.attachment()
                .filename(f.fileNm(), StandardCharsets.UTF_8)
                .build();
        HttpHeaders headers = new HttpHeaders();
        headers.setContentDisposition(cd);
        long len = f.path().toFile().length();
        if (len > 0) {
            headers.setContentLength(len);
        }
        return ResponseEntity.ok()
                .headers(headers)
                .contentType(contentType != null ? MediaType.parseMediaType(contentType) : MediaType.APPLICATION_OCTET_STREAM)
                .body(resource);
    }

    @Operation(summary = "첨부 삭제")
    @DeleteMapping("/{id}")
    public ApiResponse<Void> delete(@PathVariable("id") Long id) {
        attachmentService.delete(id);
        return ApiResponse.ok(null);
    }
}
