package fetch

import (
	"context"

	"bsm/full/module/base/ads/internal/impl"
	"bsm/full/module/base/ads/internal/models"
	pb "bsm/full/module/base/ads/pb"
	"git.apinb.com/bsm-sdk/core/errcode"
)

// 通过广告位获取广告信息
func ByPos(ctx context.Context, in *pb.ByPosRequest) (reply *pb.ByPosReply, err error) {
	// 参数验证
	if in.Key == "" {
		return nil, errcode.ErrInvalidArgument
	}

	// 从数据库查询
	var adsItems []models.AdsItem
	err = impl.DBService.Where("pos_key = ? AND status = ?", in.Key, 1).Find(&adsItems).Error
	if err != nil {
		return nil, errcode.ErrDB
	}

	// 转换为protobuf格式
	result := make([]*pb.AdsItem, 0, len(adsItems))
	for _, item := range adsItems {
		result = append(result, &pb.AdsItem{
			Id:      int64(item.ID),
			Title:   item.Title,
			Content: item.Content,
			Type:    int32(item.Type),
			ToUrl:   item.ToUrl,
			Created: item.CreatedAt.Format("2006-01-02 15:04:05"),
		})
	}

	return &pb.ByPosReply{Data: result}, nil
}
