package com.zioinfo.cms.form;

import com.zioinfo.cms.ai.AiService;
import com.zioinfo.cms.common.ApiResponse;
import com.zioinfo.cms.form.mapper.FormMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.*;

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

/**
 * 폼빌더 API — 폼 정의 CRUD + 제출 수집(AI 스팸 필터).
 */
@RestController
@RequestMapping("/api/cms/form")
@RequiredArgsConstructor
public class FormController {

    private final FormMapper mapper;
    private final AiService aiService;

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

    @GetMapping("/{id}")
    public ApiResponse<CmsForm> get(@PathVariable Long id) {
        CmsForm f = mapper.findById(id);
        if (f == null) throw new RuntimeException("ERR-CMS-FORM-404: 폼 없음");
        return ApiResponse.ok(f);
    }

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

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

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

    /** 폼 제출 — AI 스팸 판정 후 수집. */
    @PostMapping("/{id}/submit")
    public ApiResponse<CmsFormSubmission> submit(@PathVariable Long id, @RequestBody Map<String, Object> payload) {
        if (mapper.findById(id) == null) throw new RuntimeException("ERR-CMS-FORM-404: 폼 없음");
        CmsFormSubmission s = new CmsFormSubmission();
        s.setFormId(id);
        s.setPayload(jsonStr(payload));
        Map<String, Object> mod = aiService.moderate(jsonStr(payload));
        double risk = toDouble(mod.get("risk"));
        s.setSpamRisk(risk);
        s.setSpam(risk >= 0.7);
        mapper.insertSubmission(s);
        return ApiResponse.ok(s);
    }

    /** 제출 목록 조회 (기본 스팸 제외). */
    @GetMapping("/{id}/submissions")
    public ApiResponse<List<CmsFormSubmission>> submissions(@PathVariable Long id,
                                                            @RequestParam(defaultValue = "false") boolean includeSpam) {
        return ApiResponse.ok(mapper.findSubmissions(id, includeSpam));
    }

    private CmsForm bind(CmsForm f, Map<String, Object> r) {
        if (r.containsKey("name")) f.setName(str(r.get("name")));
        if (r.containsKey("slug")) f.setSlug(str(r.get("slug")));
        if (r.containsKey("fields")) f.setFields(jsonStr(r.get("fields")));
        if (r.containsKey("active")) f.setActive(Boolean.parseBoolean(String.valueOf(r.get("active"))));
        return f;
    }

    private String str(Object o) { return o == null ? null : String.valueOf(o); }
    private double toDouble(Object o) { if (o == null) return 0; try { return Double.parseDouble(String.valueOf(o)); } catch (Exception e) { return 0; } }
    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); }
    }
}
