package httpapi

import (
	"context"
	"fmt"
	"net/http"

	"github.com/easyai/easyai-ai-gateway/apps/api/internal/auth"
	"github.com/easyai/easyai-ai-gateway/apps/api/internal/store"
)

type gatewayTaskCreationStage string

const (
	gatewayTaskCreationPrepare gatewayTaskCreationStage = "prepare"
	gatewayTaskCreationStore   gatewayTaskCreationStage = "store"
)

type gatewayTaskCreationError struct {
	Stage gatewayTaskCreationStage
	Err   error
}

func (e *gatewayTaskCreationError) Error() string {
	if e == nil || e.Err == nil {
		return "gateway task creation failed"
	}
	return e.Err.Error()
}

func (e *gatewayTaskCreationError) Unwrap() error {
	if e == nil {
		return nil
	}
	return e.Err
}

func (s *Server) prepareAndCreateGatewayTask(
	ctx context.Context,
	r *http.Request,
	user *auth.User,
	kind string,
	model string,
	body map[string]any,
	async bool,
) (store.GatewayTask, error) {
	admission, err := s.authorizeTaskTraffic(r, user)
	if err != nil {
		return store.GatewayTask{}, &gatewayTaskCreationError{Stage: gatewayTaskCreationPrepare, Err: err}
	}
	prepared, err := s.prepareTaskRequest(ctx, r, user, body)
	if err != nil {
		return store.GatewayTask{}, &gatewayTaskCreationError{Stage: gatewayTaskCreationPrepare, Err: err}
	}
	runMode, err := s.admittedTaskRunMode(admission, prepared.Body)
	if err != nil {
		return store.GatewayTask{}, &gatewayTaskCreationError{Stage: gatewayTaskCreationPrepare, Err: err}
	}
	task, err := s.store.CreateTask(ctx, store.CreateTaskInput{
		Kind:            kind,
		Model:           model,
		RunMode:         runMode,
		AcceptanceRunID: admission.AcceptanceRunID,
		Async:           async,
		Request:         prepared.Body,
		ConversationID:  prepared.ConversationID,
		NewMessageCount: prepared.NewMessageCount,
		MessageRefs:     prepared.MessageRefs,
	}, user)
	if err != nil {
		return store.GatewayTask{}, &gatewayTaskCreationError{
			Stage: gatewayTaskCreationStore,
			Err:   fmt.Errorf("create task: %w", err),
		}
	}
	return task, nil
}
