package job

import (
	"context"

	"haixun-backend/internal/model/job/domain/entity"
	domusecase "haixun-backend/internal/model/job/domain/usecase"
	"haixun-backend/internal/svc"
	"haixun-backend/internal/types"
)

type UpsertJobTemplateLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewUpsertJobTemplateLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UpsertJobTemplateLogic {
	return &UpsertJobTemplateLogic{ctx: ctx, svcCtx: svcCtx}
}

func (l *UpsertJobTemplateLogic) UpsertJobTemplate(req *types.UpsertJobTemplateReq) (*types.JobTemplateData, error) {
	if err := requireAdmin(l.ctx, l.svcCtx); err != nil {
		return nil, err
	}
	template, err := l.svcCtx.Job.UpsertTemplate(l.ctx, domusecase.UpsertTemplateRequest{
		Type:              req.Type,
		Version:           req.Version,
		Name:              req.Name,
		Description:       req.Description,
		Enabled:           req.Enabled,
		Repeatable:        req.Repeatable,
		ConcurrencyPolicy: req.ConcurrencyPolicy,
		DedupeKeys:        req.DedupeKeys,
		TimeoutSeconds:    req.TimeoutSeconds,
		CancelPolicy: entity.CancelPolicy{
			Supported:    req.CancelPolicy.Supported,
			Mode:         req.CancelPolicy.Mode,
			GraceSeconds: req.CancelPolicy.GraceSeconds,
		},
		RetryPolicy: entity.RetryPolicy{
			MaxAttempts:    req.RetryPolicy.MaxAttempts,
			BackoffSeconds: req.RetryPolicy.BackoffSeconds,
		},
		Steps: toTemplateSteps(req.Steps),
	})
	if err != nil {
		return nil, err
	}
	data := toJobTemplateData(template)
	return &data, nil
}
