package workitempipeline

import (
	"context"

	"github.com/nomadcode/nomadcode-core/internal/storage"
	"github.com/nomadcode/nomadcode-core/internal/workflow"
	"github.com/nomadcode/nomadcode-core/internal/workitem"
)

type CreateTaskInput struct {
	Ref     workitem.Ref
	StateID string
	Comment string
}

type TaskCreator interface {
	CreateTask(ctx context.Context, input workflow.CreateTaskInput) (storage.Task, error)
}

type Service struct {
	reader workitem.Reader
	tasks  TaskCreator
}

func New(reader workitem.Reader, tasks TaskCreator) *Service {
	return &Service{reader: reader, tasks: tasks}
}

func (s *Service) CreateTaskFromWorkItem(ctx context.Context, input CreateTaskInput) (storage.Task, error) {
	item, err := s.reader.FetchWorkItem(ctx, input.Ref)
	if err != nil {
		return storage.Task{}, err
	}
	createInput, err := workitem.BuildCreateTaskInput(workitem.TaskCreateInput{
		Ref:     input.Ref,
		StateID: input.StateID,
		Comment: input.Comment,
	}, item)
	if err != nil {
		return storage.Task{}, err
	}
	return s.tasks.CreateTask(ctx, createInput)
}
