package com.ycwl.basic.controller.mobile.notify;

import com.ycwl.basic.annotation.IgnoreToken;
import com.ycwl.basic.model.mobile.notify.resp.WechatSubscribeAllScenesResp;
import com.ycwl.basic.model.mobile.notify.resp.WechatSubscribeSceneTemplatesResp;
import com.ycwl.basic.model.pc.notify.entity.WechatSubscribeTemplateConfigEntity;
import com.ycwl.basic.service.notify.WechatSubscribeNotifyConfigService;
import com.ycwl.basic.utils.ApiResponse;
import com.ycwl.basic.utils.JwtTokenUtil;
import com.ycwl.basic.utils.NotificationAuthUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * 微信小程序订阅消息：场景模板查询（移动端API）
 *
 * @Author: System
 * @Date: 2025/12/31
 */
@RestController
@RequestMapping("/api/mobile/notify/subscribe")
@Slf4j
public class WechatSubscribeNotifyController {

    private final WechatSubscribeNotifyConfigService configService;
    private final NotificationAuthUtils notificationAuthUtils;

    public WechatSubscribeNotifyController(WechatSubscribeNotifyConfigService configService,
                                           NotificationAuthUtils notificationAuthUtils) {
        this.configService = configService;
        this.notificationAuthUtils = notificationAuthUtils;
    }

    /**
     * 获取“场景”下可申请授权的模板列表（支持按 scenicId 覆盖模板ID/开关/文案）
     */
    @GetMapping("/scenic/{scenicId}/scenes/{sceneKey}/templates")
    @IgnoreToken
    public ApiResponse<WechatSubscribeSceneTemplatesResp> listSceneTemplates(@PathVariable("scenicId") Long scenicId,
                                                                             @PathVariable("sceneKey") String sceneKey) {
        if (scenicId == null) {
            return ApiResponse.fail("scenicId不能为空");
        }
        if (StringUtils.isBlank(sceneKey)) {
            return ApiResponse.fail("sceneKey不能为空");
        }

        Long memberId = JwtTokenUtil.getWorker().getUserId();
        List<WechatSubscribeTemplateConfigEntity> configs = configService.listSceneTemplateConfigs(scenicId, sceneKey);

        WechatSubscribeSceneTemplatesResp resp = new WechatSubscribeSceneTemplatesResp();
        resp.setScenicId(scenicId);
        resp.setSceneKey(sceneKey);
        if (memberId == null) {
            return ApiResponse.success(resp);
        }

        List<WechatSubscribeSceneTemplatesResp.TemplateInfo> templates = new ArrayList<>();
        for (WechatSubscribeTemplateConfigEntity cfg : configs) {
            if (cfg == null || StringUtils.isBlank(cfg.getWechatTemplateId())) {
                continue;
            }
            String title = StringUtils.isNotBlank(cfg.getTitleTemplate())
                    ? cfg.getTitleTemplate()
                    : cfg.getTemplateKey();
            int remaining = notificationAuthUtils.getRemainingCount(memberId, cfg.getWechatTemplateId(), scenicId);

            WechatSubscribeSceneTemplatesResp.TemplateInfo info = new WechatSubscribeSceneTemplatesResp.TemplateInfo();
            info.setTemplateKey(cfg.getTemplateKey());
            info.setWechatTemplateId(cfg.getWechatTemplateId());
            info.setTitle(title);
            info.setDescription(cfg.getDescription());
            info.setRemainingCount(remaining);
            info.setHasAuthorization(remaining > 0);
            templates.add(info);
        }
        resp.setTemplates(templates);

        log.debug("场景模板查询: scenicId={}, sceneKey={}, memberId={}, templateCount={}",
                scenicId, sceneKey, memberId, Objects.requireNonNullElse(templates.size(), 0));
        return ApiResponse.success(resp);
    }

    /**
     * 获取景区下所有场景及其模板列表（静态配置，带缓存）
     * 不含用户授权信息，用户授权信息通过 /api/mobile/notify/auth/batch-remaining 接口获取
     */
    @GetMapping("/scenic/{scenicId}/scenes")
    @IgnoreToken
    public ApiResponse<WechatSubscribeAllScenesResp> listAllSceneTemplates(@PathVariable("scenicId") Long scenicId) {
        if (scenicId == null) {
            return ApiResponse.fail("scenicId不能为空");
        }

        WechatSubscribeAllScenesResp resp = configService.getAllScenesWithTemplatesCached(scenicId);
        log.debug("所有场景模板查询: scenicId={}, sceneCount={}",
                scenicId, resp.getScenes() != null ? resp.getScenes().size() : 0);
        return ApiResponse.success(resp);
    }
}

