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

package brand

import (
	"context"
	"strings"

	jobdom "haixun-backend/internal/model/job/domain/usecase"
	"haixun-backend/internal/svc"
	"haixun-backend/internal/types"

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

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

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

func (l *UpsertBrandScanScheduleLogic) UpsertBrandScanSchedule(req *types.UpsertBrandScanScheduleHandlerReq) (resp *types.BrandScanScheduleData, err error) {
	tenantID, uid, err := actorFrom(l.ctx)
	if err != nil {
		return nil, err
	}
	if _, err := l.svcCtx.Brand.Get(l.ctx, tenantID, uid, req.ID); err != nil {
		return nil, err
	}

	cronExpr := "0 9 * * *"
	timezone := "Asia/Taipei"
	enabled := false
	if strings.TrimSpace(req.Cron) != "" {
		cronExpr = strings.TrimSpace(req.Cron)
	}
	if strings.TrimSpace(req.Timezone) != "" {
		timezone = strings.TrimSpace(req.Timezone)
	}
	enabled = req.Enabled

	research, err := l.svcCtx.Placement.ResearchSettings(l.ctx, tenantID, uid)
	if err != nil {
		return nil, err
	}
	memberCtx, err := l.svcCtx.ThreadsAccount.ResolveMemberPlacementContext(l.ctx, tenantID, uid, research)
	if err != nil {
		return nil, err
	}

	payload := map[string]any{
		"brand_id":   req.ID,
		"dual_track": true,
		"scheduled":  true,
	}
	for key, value := range memberCtx.PayloadFields() {
		payload[key] = value
	}

	existing, err := findBrandPlacementSchedule(l.ctx, l.svcCtx, req.ID)
	if err != nil {
		return nil, err
	}
	if existing != nil {
		updated, err := l.svcCtx.Job.UpdateSchedule(l.ctx, jobdom.UpdateScheduleRequest{
			ID:              existing.ID.Hex(),
			Cron:            cronExpr,
			Timezone:        timezone,
			PayloadTemplate: payload,
			Enabled:         &enabled,
		})
		if err != nil {
			return nil, err
		}
		return toBrandScanScheduleData(updated, req.ID), nil
	}

	created, err := l.svcCtx.Job.CreateSchedule(l.ctx, jobdom.CreateScheduleRequest{
		TemplateType:    placementScanTemplate,
		Scope:           "brand",
		ScopeID:         req.ID,
		Cron:            cronExpr,
		Timezone:        timezone,
		PayloadTemplate: payload,
		Enabled:         enabled,
	})
	if err != nil {
		return nil, err
	}
	return toBrandScanScheduleData(created, req.ID), nil
}
