// Code scaffolded by goctl. Safe to edit.
// goctl 1.10.1

package threads_account

import (
	"context"

	inventorydomain "haixun-backend/internal/model/publish_inventory/domain/usecase"
	"haixun-backend/internal/svc"
	"haixun-backend/internal/types"

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

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

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

func (l *UpsertPublishInventoryPolicyLogic) UpsertPublishInventoryPolicy(req *types.UpsertPublishInventoryPolicyHandlerReq) (resp *types.PublishInventoryPolicyData, err error) {
	tenantID, uid, err := actorFrom(l.ctx)
	if err != nil {
		return nil, err
	}
	slots := make([]inventorydomain.Slot, 0, len(req.Slots))
	for _, slot := range req.Slots {
		slots = append(slots, inventorydomain.Slot{Weekday: slot.Weekday, Time: slot.Time})
	}
	refs := make([]inventorydomain.SourceRef, 0, len(req.SourceRefs))
	for _, ref := range req.SourceRefs {
		refs = append(refs, inventorydomain.SourceRef{
			Type: ref.Type, PersonaID: ref.PersonaID, CopyMissionID: ref.CopyMissionID,
			ScanPostID: ref.ScanPostID, ManualSeed: ref.ManualSeed,
		})
	}
	item, err := l.svcCtx.PublishInventory.Upsert(l.ctx, inventorydomain.UpsertRequest{
		TenantID: tenantID, OwnerUID: uid, AccountID: req.ID, Enabled: req.Enabled,
		TargetDailyCount: req.TargetDailyCount, LowStockThreshold: req.LowStockThreshold,
		LookaheadDays: req.LookaheadDays, Timezone: req.Timezone, Slots: slots, SourceRefs: refs,
	})
	if err != nil {
		return nil, err
	}
	return toInventoryPolicyData(item), nil
}
