package com.zioinfo.cms.media;

import com.zioinfo.cms.admin.AuditService;
import com.zioinfo.cms.ai.AiService;
import com.zioinfo.cms.media.mapper.MediaMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

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

/**
 * 미디어 라이브러리 서비스 — 메타 등록 + AI 대체텍스트/태깅(llava 폴백).
 */
@Service
@RequiredArgsConstructor
public class MediaService {

    private final MediaMapper mapper;
    private final AiService aiService;
    private final AuditService auditService;

    public List<CmsMedia> list(String folder, String mediaType, String keyword) {
        return mapper.findAll(folder, mediaType, keyword);
    }

    public CmsMedia get(Long id) {
        CmsMedia m = mapper.findById(id);
        if (m == null) throw new RuntimeException("ERR-CMS-MEDIA-404: 미디어 없음");
        return m;
    }

    /** 미디어 메타 등록 (업로드 자체는 url 전달 — 실 파일저장은 프론트/스토리지 책임). */
    public CmsMedia register(Map<String, Object> req, String actor) {
        CmsMedia m = new CmsMedia();
        m.setFileName(str(req.get("fileName")));
        m.setMediaType(req.get("mediaType") == null ? "IMAGE" : str(req.get("mediaType")));
        m.setUrl(str(req.get("url")));
        m.setFolder(req.get("folder") == null ? "default" : str(req.get("folder")));
        m.setMimeType(str(req.get("mimeType")));
        m.setSizeBytes(longOf(req.get("sizeBytes")));
        m.setAltText(str(req.get("altText")));
        m.setTags(str(req.get("tags")));
        m.setRefCount(0);
        m.setCreatedBy(actor);
        mapper.insert(m);
        auditService.log("MEDIA_REGISTER", m.getFileName(), m.getMediaType());
        return mapper.findById(m.getId());
    }

    /** AI 대체텍스트/태깅 (base64 이미지 또는 파일명 폴백). */
    public CmsMedia autoTag(Long id, String imageBase64) {
        CmsMedia m = get(id);
        Map<String, Object> ai = aiService.imageTags(imageBase64, m.getFileName());
        String alt = String.valueOf(ai.getOrDefault("altText", m.getAltText()));
        Object tagsObj = ai.get("tags");
        String tags = tagsObj instanceof List<?> l ? String.join(",", l.stream().map(String::valueOf).toList())
                : String.valueOf(tagsObj);
        mapper.updateMeta(id, alt, tags);
        auditService.log("MEDIA_AUTOTAG", m.getFileName(), "source=" + ai.getOrDefault("source", "?"));
        return mapper.findById(id);
    }

    public CmsMedia updateMeta(Long id, String altText, String tags) {
        get(id);
        mapper.updateMeta(id, altText, tags);
        return mapper.findById(id);
    }

    public void delete(Long id) {
        CmsMedia m = get(id);
        mapper.delete(id);
        auditService.log("MEDIA_DELETE", m.getFileName(), null);
    }

    private String str(Object o) { return o == null ? null : String.valueOf(o); }
    private Long longOf(Object o) {
        if (o == null) return null;
        try { return Long.valueOf(String.valueOf(o).trim()); } catch (Exception e) { return null; }
    }
}
