package scheduler

import (
	"context"
	"log/slog"

	"github.com/nomadcode/nomadcode-core/internal/authoring"
	"github.com/nomadcode/nomadcode-core/internal/db"
	"github.com/nomadcode/nomadcode-core/internal/projectsync"
	"github.com/nomadcode/nomadcode-core/internal/storage"
)

type WorkspaceSlotStateUpdater interface {
	UpdateWorkspaceSlotState(ctx context.Context, args db.UpdateWorkspaceSlotStateParams) (db.WorkspaceSlot, error)
}

func applyTaskSlotTerminalState(ctx context.Context, updater WorkspaceSlotStateUpdater, task storage.Task, state projectsync.SlotState, logger *slog.Logger) {
	if updater == nil {
		return
	}
	checkout, ok := authoring.TaskCheckoutMetadata(task)
	if !ok || checkout.SlotID <= 0 {
		if logger != nil {
			logger.Warn("authoring task missing slot metadata; skipping slot terminal state update", "task_id", task.ID)
		}
		return
	}
	params, err := projectsync.ToUpdateWorkspaceSlotStateParams(checkout.SlotID, state)
	if err != nil {
		if logger != nil {
			logger.Warn("invalid slot terminal state; skipping slot update", "task_id", task.ID, "slot_id", checkout.SlotID, "state", string(state), "error", err)
		}
		return
	}
	if _, err := updater.UpdateWorkspaceSlotState(ctx, params); err != nil {
		if logger != nil {
			logger.Warn("workspace slot terminal state update failed", "task_id", task.ID, "slot_id", checkout.SlotID, "state", string(state), "error", err)
		}
		return
	}
	if logger != nil {
		logger.Info("workspace slot terminal state updated", "task_id", task.ID, "slot_id", checkout.SlotID, "state", string(state))
	}
}
