package com.zioinfo.cms.theme;

import com.zioinfo.cms.common.ApiResponse;
import com.zioinfo.cms.theme.mapper.ThemeMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.security.core.Authentication;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

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

/** 테마/템플릿 API. 단일 활성 테마 보장. */
@RestController
@RequestMapping("/api/cms/theme")
@RequiredArgsConstructor
public class ThemeController {

    private final ThemeMapper mapper;

    @GetMapping
    public ApiResponse<List<CmsTheme>> list() {
        return ApiResponse.ok(mapper.findAll());
    }

    @GetMapping("/active")
    public ApiResponse<CmsTheme> active() {
        return ApiResponse.ok(mapper.findActive());
    }

    @GetMapping("/{id}")
    public ApiResponse<CmsTheme> get(@PathVariable Long id) {
        CmsTheme t = mapper.findById(id);
        if (t == null) throw new RuntimeException("ERR-CMS-THEME-404: 테마 없음");
        return ApiResponse.ok(t);
    }

    @PostMapping
    public ApiResponse<CmsTheme> create(@RequestBody Map<String, Object> req, Authentication auth) {
        CmsTheme t = bind(new CmsTheme(), req);
        t.setCreatedBy(auth != null ? auth.getName() : "system");
        mapper.insert(t);
        return ApiResponse.ok(mapper.findById(t.getId()));
    }

    @PutMapping("/{id}")
    public ApiResponse<CmsTheme> update(@PathVariable Long id, @RequestBody Map<String, Object> req) {
        CmsTheme t = mapper.findById(id);
        if (t == null) throw new RuntimeException("ERR-CMS-THEME-404: 테마 없음");
        bind(t, req);
        mapper.update(t);
        return ApiResponse.ok(mapper.findById(id));
    }

    /** 테마 활성화 (단일 활성 보장). */
    @PostMapping("/{id}/activate")
    @Transactional
    public ApiResponse<CmsTheme> activate(@PathVariable Long id) {
        if (mapper.findById(id) == null) throw new RuntimeException("ERR-CMS-THEME-404: 테마 없음");
        mapper.deactivateAll();
        mapper.activate(id);
        return ApiResponse.ok(mapper.findById(id));
    }

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

    private CmsTheme bind(CmsTheme t, Map<String, Object> r) {
        if (r.containsKey("name")) t.setName(str(r.get("name")));
        if (r.containsKey("layout")) t.setLayout(jsonStr(r.get("layout")));
        if (r.containsKey("tokens")) t.setTokens(jsonStr(r.get("tokens")));
        if (r.containsKey("active")) t.setActive(Boolean.parseBoolean(String.valueOf(r.get("active"))));
        return t;
    }

    private String str(Object o) { return o == null ? null : String.valueOf(o); }
    private String jsonStr(Object o) {
        if (o == null) return null;
        if (o instanceof String s) return s;
        try { return new com.fasterxml.jackson.databind.ObjectMapper().writeValueAsString(o); } catch (Exception e) { return String.valueOf(o); }
    }
}
