package com.zioinfo.kintex.cms;

import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;

import java.util.Map;

/**
 * M17 마이크로사이트 매퍼 — 참가업체별 공개 소개 페이지. ★Map 별칭 쌍따옴표 필수.
 * sections 는 jsonb → sections::text 로 원문 문자열 반환(서비스에서 JsonNode 파싱).
 */
@Mapper
public interface MicrositeMapper {

    @Select("""
            SELECT exhibitor_id AS "exhibitorId", event_id AS "eventId", slug,
                   exhibitor_name AS "exhibitorName", theme, sections::text AS "sections",
                   seo_title AS "seoTitle", seo_meta AS "seoMeta", langs, status,
                   to_char(published_at AT TIME ZONE 'UTC','YYYY-MM-DD"T"HH24:MI:SS"Z"') AS "publishedAt",
                   to_char(updated_at AT TIME ZONE 'UTC','YYYY-MM-DD"T"HH24:MI:SS"Z"') AS "updatedAt"
            FROM microsite WHERE exhibitor_id = #{exhibitorId}
            """)
    Map<String, Object> findByExhibitor(@Param("exhibitorId") String exhibitorId);

    /** upsert(멱등) — sections 는 jsonb 캐스팅. published 전이 시 published_at=now(). */
    @Insert("""
            INSERT INTO microsite (exhibitor_id, event_id, slug, exhibitor_name, theme, sections,
                                   seo_title, seo_meta, langs, status, published_at, updated_at)
            VALUES (#{exhibitorId}, #{eventId}, #{slug}, #{exhibitorName}, COALESCE(#{theme},'blue'),
                    CAST(COALESCE(#{sectionsJson},'[]') AS jsonb), #{seoTitle}, #{seoMeta},
                    COALESCE(#{langs},'ko'), COALESCE(#{status},'draft'),
                    CASE WHEN #{status} = 'published' THEN now() ELSE NULL END, now())
            ON CONFLICT (exhibitor_id) DO UPDATE
               SET event_id = EXCLUDED.event_id,
                   slug = EXCLUDED.slug,
                   exhibitor_name = EXCLUDED.exhibitor_name,
                   theme = EXCLUDED.theme,
                   sections = EXCLUDED.sections,
                   seo_title = EXCLUDED.seo_title,
                   seo_meta = EXCLUDED.seo_meta,
                   langs = EXCLUDED.langs,
                   status = EXCLUDED.status,
                   published_at = CASE WHEN EXCLUDED.status = 'published' THEN now()
                                       ELSE microsite.published_at END,
                   updated_at = now()
            """)
    int upsert(Map<String, Object> p);
}
