package com.zioinfo.kintex.cms;

import com.zioinfo.kintex.auth.EventAccessGuard;
import com.zioinfo.kintex.auth.KintexPrincipal;
import com.zioinfo.kintex.cms.dto.CmsMediaDto;
import com.zioinfo.kintex.common.ApiResponse;
import com.zioinfo.kintex.common.audit.Audited;
import org.springframework.http.MediaType;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

/**
 * M17 CMS 미디어 라이브러리 API (SCR-35 중앙 미디어 스트립). 인증 필수.
 * 업로드는 기존 패턴(login-slides) 재사용 — 서버가 UUID 파일명 강제, /uploads/cms/** 로 서빙.
 * <ul>
 *   <li>GET  /api/cms/media?eventId=&limit= — 최신순 목록</li>
 *   <li>POST /api/cms/media (multipart: file[+eventId,altText]) — 업로드</li>
 * </ul>
 */
@RestController
@RequestMapping("/api/cms/media")
public class CmsMediaController {

    private final CmsService service;
    private final EventAccessGuard guard;

    public CmsMediaController(CmsService service, EventAccessGuard guard) {
        this.service = service;
        this.guard = guard;
    }

    @GetMapping
    public ApiResponse<List<CmsMediaDto>> list(@AuthenticationPrincipal KintexPrincipal principal,
                                               @RequestParam(required = false) String eventId,
                                               @RequestParam(defaultValue = "60") int limit) {
        guard.require(principal);
        return ApiResponse.ok(service.mediaList(eventId, limit));
    }

    @Audited(action = "CMS_MEDIA_UPLOAD", targetType = "cms_media")
    @PostMapping(consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public ApiResponse<CmsMediaDto> upload(@AuthenticationPrincipal KintexPrincipal principal,
                                           @RequestPart("file") MultipartFile file,
                                           @RequestParam(value = "eventId", required = false) String eventId,
                                           @RequestParam(value = "altText", required = false) String altText) {
        guard.require(principal);
        return ApiResponse.ok(service.addMedia(principal, file, eventId, altText));
    }
}
