package org.jeecg.modules.adweb.dmp.controller;

import io.swagger.v3.oas.annotations.tags.Tag;

import lombok.extern.slf4j.Slf4j;

import org.apache.commons.lang3.tuple.Pair;
import org.jeecg.common.api.vo.Result;
import org.jeecg.modules.adweb.dmp.entity.GoogleGTM;
import org.jeecg.modules.adweb.dmp.service.google.GTMAdminService;
import org.jeecg.modules.adweb.site.entity.AdwebSite;
import org.jeecg.modules.adweb.site.service.IAdwebSiteService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.Objects;

/**
 * GTM容器和标签管理
 *
 * @author wfansh
 */
@Tag(name = "Google Tag Manager")
@RestController
@RequestMapping("/gtm")
@Slf4j
public class GTMController {

    @Autowired private IAdwebSiteService adwebSiteService;

    @Autowired private GTMAdminService gtmAdminService;

    @RequestMapping(value = "/add", method = RequestMethod.POST)
    @ResponseBody
    public Result<Pair<String, String>> addContainer(String siteCode) {
        AdwebSite adwebSite = adwebSiteService.getSiteByCode(siteCode);
        if (Objects.isNull(adwebSite)) {
            return Result.error("站点未找到" + siteCode);
        }

        // 如果GoogleGTM表中已存在，不再创建，返回现有记录
        GoogleGTM googleGTM =
                gtmAdminService.createContainer(
                        adwebSite.getCode(), adwebSite.getDomain(), adwebSite.getName());
        return Result.ok(gtmAdminService.getSnippets(googleGTM.getGtmTagId()));
    }
}
