package kr.lunaticbum.back.lun.controllers.api

import kr.lunaticbum.back.lun.model.ImageMeta
import kr.lunaticbum.back.lun.model.ImageMetaService
import kr.lunaticbum.back.lun.model.ImageUploadResponse
import kr.lunaticbum.back.lun.services.ImageService // [Import 추가]
import org.springframework.http.ResponseEntity
import org.springframework.security.access.prepost.PreAuthorize
import org.springframework.web.bind.annotation.*
import org.springframework.web.multipart.MultipartFile
import reactor.core.publisher.Mono

@RestController
@RequestMapping("/api/images")
class ImageApiController(
    private val imageService: ImageService, // [주입]
    private val imageMetaService: ImageMetaService
) {

    @GetMapping("/{filename:.+}")
    suspend fun getImage(
        @PathVariable filename: String,
        @RequestParam(required = false) type: String?
    ): ResponseEntity<ByteArray> {
        // 모든 로직을 서비스로 위임
        return imageService.loadImage(filename, type)
    }

    @PostMapping("/upload")
    suspend fun uploadImage(@RequestParam("file") file: MultipartFile): Mono<ImageUploadResponse> {
        return imageService.saveImage(file)
    }

    // (배너 승인/해제 메서드는 그대로 유지)
    @PostMapping("/{imageId}/approve-banner")
    @PreAuthorize("hasRole('ADMIN')")
    fun approveBannerImage(@PathVariable imageId: String): Mono<ResponseEntity<ImageMeta>> {
        return imageMetaService.approveForBanner(imageId)
            .map { ResponseEntity.ok(it) }
            .defaultIfEmpty(ResponseEntity.notFound().build())
    }

    @PostMapping("/{imageId}/revoke-banner")
    @PreAuthorize("hasRole('ADMIN')")
    fun revokeBannerImage(@PathVariable imageId: String): Mono<ResponseEntity<ImageMeta>> {
        return imageMetaService.revokeBannerApproval(imageId)
            .map { ResponseEntity.ok(it) }
            .defaultIfEmpty(ResponseEntity.notFound().build())
    }
}