package com.zioinfo.cms.content;

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

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

/**
 * 콘텐츠 관리 API (헤드리스 페이지/포스트/블록).
 *
 * <p>RBAC: 조회 Viewer+, 작성/수정/삭제 Author+, 워크플로우 승인/발행은 서비스에서 Editor+ 가드.
 */
@RestController
@RequestMapping("/api/cms/content")
@RequiredArgsConstructor
public class ContentController {

    private final ContentService service;

    @GetMapping
    public ApiResponse<List<CmsContent>> list(
            @RequestParam(required = false) String contentType,
            @RequestParam(required = false) String status,
            @RequestParam(required = false) String locale,
            @RequestParam(required = false) String keyword) {
        return ApiResponse.ok(service.list(contentType, status, locale, keyword));
    }

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

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

    @PostMapping
    public ApiResponse<CmsContent> create(@RequestBody Map<String, Object> req, Authentication auth) {
        return ApiResponse.ok(service.create(req, actor(auth)));
    }

    @PutMapping("/{id}")
    public ApiResponse<CmsContent> update(@PathVariable Long id, @RequestBody Map<String, Object> req, Authentication auth) {
        return ApiResponse.ok(service.update(id, req, actor(auth)));
    }

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

    /** 워크플로우 전이 (submit/approve/publish/reject/archive/schedule). */
    @PostMapping("/{id}/transition")
    public ApiResponse<CmsContent> transition(@PathVariable Long id,
                                              @RequestBody TransitionRequest req,
                                              Authentication auth) {
        LocalDateTime scheduledAt = (req.scheduledAt() == null || req.scheduledAt().isBlank())
                ? null : LocalDateTime.parse(req.scheduledAt());
        return ApiResponse.ok(service.transition(id, req.action(), req.note(), scheduledAt, actor(auth), role(auth)));
    }

    /** 버전 롤백. */
    @PostMapping("/{id}/rollback")
    public ApiResponse<CmsContent> rollback(@PathVariable Long id, @RequestBody RollbackRequest req, Authentication auth) {
        return ApiResponse.ok(service.rollback(id, req.version(), actor(auth)));
    }

    private String actor(Authentication a) {
        return a != null ? a.getName() : "system";
    }

    private String role(Authentication a) {
        if (a == null || a.getAuthorities().isEmpty()) return "VIEWER";
        String r = a.getAuthorities().iterator().next().getAuthority();
        return r.startsWith("ROLE_") ? r.substring(5) : r;
    }

    record TransitionRequest(String action, String note, String scheduledAt) {}
    record RollbackRequest(Integer version) {}
}
