package agent

import (
	"context"
	"strings"

	"bdqr-server/app/main/api/internal/svc"
	"bdqr-server/app/main/api/internal/types"
	"bdqr-server/common/xerr"
	"bdqr-server/app/main/model"

	"github.com/pkg/errors"
	"github.com/zeromicro/go-zero/core/logx"
)

type CheckFeatureWhitelistStatusLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewCheckFeatureWhitelistStatusLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CheckFeatureWhitelistStatusLogic {
	return &CheckFeatureWhitelistStatusLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *CheckFeatureWhitelistStatusLogic) CheckFeatureWhitelistStatus(req *types.CheckFeatureWhitelistStatusReq) (resp *types.CheckFeatureWhitelistStatusResp, err error) {
	// 1. 验证参数
	if req.IdCard == "" {
		return nil, errors.Wrapf(xerr.NewErrMsg("身份证号不能为空"), "")
	}
	if req.FeatureApiId == "" {
		return nil, errors.Wrapf(xerr.NewErrMsg("模块API标识不能为空"), "")
	}

	// 2. 提取主模块ID（去掉下划线后的部分）
	mainApiId := req.FeatureApiId
	if idx := strings.Index(req.FeatureApiId, "_"); idx > 0 {
		mainApiId = req.FeatureApiId[:idx]
	}

	// 3. 查询feature信息（使用主模块ID）
	feature, err := l.svcCtx.FeatureModel.FindOneByApiId(l.ctx, mainApiId)
	if err != nil {
		if errors.Is(err, model.ErrNotFound) {
			return nil, errors.Wrapf(xerr.NewErrMsg("模块不存在"), "")
		}
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "查询模块信息失败, %v", err)
	}

	// 4. 检查是否在白名单中（使用主模块ID）
	whitelistBuilder := l.svcCtx.UserFeatureWhitelistModel.SelectBuilder().
		Where("id_card = ? AND feature_api_id = ? AND status = ?", req.IdCard, mainApiId, 1)
	whitelists, err := l.svcCtx.UserFeatureWhitelistModel.FindAll(l.ctx, whitelistBuilder, "")
	if err != nil {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "查询白名单记录失败, %v", err)
	}

	isWhitelisted := len(whitelists) > 0

	// 5. 如果提供了 queryId，检查当前报告数据是否已删除
	dataDeleted := false
	if req.QueryId != "" {
		containsFeature, err := l.svcCtx.WhitelistService.CheckQueryDataContainsFeature(l.ctx, req.QueryId, req.FeatureApiId)
		if err != nil {
			// 检查失败不影响主流程，记录日志即可
			logx.Errorf("检查报告数据是否包含模块失败：查询记录 %s，模块 %s，错误：%v", req.QueryId, req.FeatureApiId, err)
			// 默认认为数据已删除（保守处理）
			dataDeleted = true
		} else {
			// 如果数据中不包含该模块，说明已删除
			dataDeleted = !containsFeature
		}
	} else {
		// 未提供 queryId，无法判断数据是否已删除，默认认为已删除（保守处理）
		dataDeleted = true
	}

	return &types.CheckFeatureWhitelistStatusResp{
		IsWhitelisted:  isWhitelisted,
		WhitelistPrice: feature.WhitelistPrice,
		FeatureId:      feature.Id,
		DataDeleted:    dataDeleted,
	}, nil
}
