package admin_agent

import (
	"context"
	"sim-server/common/xerr"

	"github.com/pkg/errors"

	"sim-server/app/main/api/internal/svc"
	"sim-server/app/main/api/internal/types"

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

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

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

func (l *AdminGetAgentProductConfigListLogic) AdminGetAgentProductConfigList(req *types.AdminGetAgentProductConfigListReq) (resp *types.AdminGetAgentProductConfigListResp, err error) {
	builder := l.svcCtx.AgentProductConfigModel.SelectBuilder()

	// 如果提供了产品ID，直接过滤
	if req.ProductId != nil {
		builder = builder.Where("product_id = ?", *req.ProductId)
	}

	// 如果提供了产品名称，通过关联查询 product 表过滤
	if req.ProductName != nil && *req.ProductName != "" {
		builder = builder.Where("product_id IN (SELECT id FROM product WHERE product_name LIKE ?)", "%"+*req.ProductName+"%")
	}

	// 分页查询
	page := req.Page
	if page <= 0 {
		page = 1
	}
	pageSize := req.PageSize
	if pageSize <= 0 {
		pageSize = 20
	}

	configs, total, err := l.svcCtx.AgentProductConfigModel.FindPageListByPageWithTotal(l.ctx, builder, page, pageSize, "id DESC")
	if err != nil {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "查询产品配置列表失败, %v", err)
	}

	// 组装响应（通过 product_id 查询产品名称）
	items := make([]types.AgentProductConfigItem, 0, len(configs))
	for _, config := range configs {
		// 通过 product_id 查询产品信息获取产品名称
		product, err := l.svcCtx.ProductModel.FindOne(l.ctx, config.ProductId)
		productName := ""
		if err == nil {
			productName = product.ProductName
		} else {
			// 如果产品不存在，记录日志但不影响主流程
			l.Infof("查询产品信息失败, productId: %d, err: %v", config.ProductId, err)
		}

		priceThreshold := 0.0
		if config.PriceThreshold.Valid {
			priceThreshold = config.PriceThreshold.Float64
		}

		priceFeeRate := 0.0
		if config.PriceFeeRate.Valid {
			priceFeeRate = config.PriceFeeRate.Float64
		}

		items = append(items, types.AgentProductConfigItem{
			Id:             config.Id,
			ProductId:      config.ProductId,
			ProductName:    productName,
			BasePrice:      config.BasePrice,
			PriceRangeMin:  config.BasePrice, // 最低定价等于基础底价
			PriceRangeMax:  config.SystemMaxPrice,
			PriceThreshold: priceThreshold,
			PriceFeeRate:   priceFeeRate,
			CreateTime:     config.CreateTime.Format("2006-01-02 15:04:05"),
		})
	}

	return &types.AdminGetAgentProductConfigListResp{
		Total: total,
		Items: items,
	}, nil
}
