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

package brand

import (
	"context"

	jobentity "haixun-backend/internal/model/job/domain/entity"
	"haixun-backend/internal/svc"
	"haixun-backend/internal/types"

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

const placementScanTemplate = "placement-scan"

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

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

func (l *GetBrandScanScheduleLogic) GetBrandScanSchedule(req *types.BrandPath) (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
	}
	schedule, err := findBrandPlacementSchedule(l.ctx, l.svcCtx, req.ID)
	if err != nil {
		return nil, err
	}
	if schedule == nil {
		return &types.BrandScanScheduleData{
			BrandID:  req.ID,
			Cron:     "0 9 * * *",
			Timezone: "Asia/Taipei",
			Enabled:  false,
		}, nil
	}
	return toBrandScanScheduleData(schedule, req.ID), nil
}

func findBrandPlacementSchedule(ctx context.Context, svcCtx *svc.ServiceContext, brandID string) (*jobentity.Schedule, error) {
	schedules, _, _, _, _, err := svcCtx.Job.ListSchedules(ctx, "brand", brandID, 1, 50)
	if err != nil {
		return nil, err
	}
	for _, schedule := range schedules {
		if schedule != nil && schedule.TemplateType == placementScanTemplate {
			return schedule, nil
		}
	}
	return nil, nil
}

func toBrandScanScheduleData(schedule *jobentity.Schedule, brandID string) *types.BrandScanScheduleData {
	if schedule == nil {
		return nil
	}
	data := &types.BrandScanScheduleData{
		ID:        schedule.ID.Hex(),
		BrandID:   brandID,
		Cron:      schedule.Cron,
		Timezone:  schedule.Timezone,
		Enabled:   schedule.Enabled,
		NextRunAt: schedule.NextRunAt,
	}
	if schedule.LastRunAt != nil {
		data.LastRunAt = *schedule.LastRunAt
	}
	return data
}
