package com.zioinfo.cms.media;

import com.zioinfo.cms.common.ApiResponse;
import lombok.RequiredArgsConstructor;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/cms/media")
@RequiredArgsConstructor
public class MediaController {

    private final MediaService service;

    @GetMapping
    public ApiResponse<List<CmsMedia>> list(@RequestParam(required = false) String folder,
                                            @RequestParam(required = false) String mediaType,
                                            @RequestParam(required = false) String keyword) {
        return ApiResponse.ok(service.list(folder, mediaType, keyword));
    }

    @GetMapping("/{id}")
    public ApiResponse<CmsMedia> get(@PathVariable Long id) {
        return ApiResponse.ok(service.get(id));
    }

    @PostMapping
    public ApiResponse<CmsMedia> register(@RequestBody Map<String, Object> req, Authentication auth) {
        return ApiResponse.ok(service.register(req, auth != null ? auth.getName() : "system"));
    }

    /** AI 대체텍스트/태깅 자동생성. */
    @PostMapping("/{id}/auto-tag")
    public ApiResponse<CmsMedia> autoTag(@PathVariable Long id, @RequestBody(required = false) Map<String, String> req) {
        String img = req == null ? null : req.get("imageBase64");
        return ApiResponse.ok(service.autoTag(id, img));
    }

    @PutMapping("/{id}/meta")
    public ApiResponse<CmsMedia> updateMeta(@PathVariable Long id, @RequestBody Map<String, String> req) {
        return ApiResponse.ok(service.updateMeta(id, req.get("altText"), req.get("tags")));
    }

    @DeleteMapping("/{id}")
    public ApiResponse<Void> delete(@PathVariable Long id) {
        service.delete(id);
        return ApiResponse.ok(null);
    }
}
