package activity

import (
	"context"
	"strings"

	"bindbox-game/internal/repository/mysql/model"
)

// CreateActivity 创建活动
// 参数: in 活动创建输入
// 返回: 新建的活动记录与错误
func (s *service) CreateActivity(ctx context.Context, in CreateActivityInput) (*model.Activities, error) {
	item := &model.Activities{
		Name:               in.Name,
		Banner:             in.Banner,
		Image:              in.Image,
		GameplayIntro:      sanitizeHTML(in.GameplayIntro),
		ActivityCategoryID: in.ActivityCategoryID,
		Status:             in.Status,
		PriceDraw:          in.PriceDraw,
		IsBoss:             in.IsBoss,
		AllowItemCards:     in.AllowItemCards != 0,
		AllowCoupons:       in.AllowCoupons != 0,
	}

	if in.StartTime != nil {
		item.StartTime = *in.StartTime
	}
	if in.EndTime != nil {
		item.EndTime = *in.EndTime
	}

	do := s.writeDB.Activities.WithContext(ctx)
	if item.Image == "" {
		do = do.Omit(s.writeDB.Activities.Image)
	}
	if item.Banner == "" {
		do = do.Omit(s.writeDB.Activities.Banner)
	}
	if strings.TrimSpace(item.GameplayIntro) == "" {
		do = do.Omit(s.writeDB.Activities.GameplayIntro)
	}
	if in.StartTime == nil || in.StartTime.IsZero() {
		do = do.Omit(s.writeDB.Activities.StartTime)
	}
	if in.EndTime == nil || in.EndTime.IsZero() {
		do = do.Omit(s.writeDB.Activities.EndTime)
	}
	// 避免零日期写入新增的时间列
	do = do.Omit(s.writeDB.Activities.ScheduledTime, s.writeDB.Activities.LastSettledAt)
	err := do.Create(item)
	if err != nil {
		return nil, err
	}
	return item, nil
}
