package dockerfile

import (
	"context"
	"errors"
	"log/slog"

	"github.com/alexei/tinyforge/internal/store"
	"github.com/alexei/tinyforge/internal/workload/plugin"
)

// teardown drops every artifact deploy created: the running container,
// the proxy route, the container index row. Idempotent — a workload
// that never deployed is a no-op.
//
// The built image tag is left in place: removing it would invalidate
// the docker build cache (next deploy of the same workload would
// rebuild from scratch). Operators can prune unused images via the
// existing Settings → Prune Images path.
func teardown(ctx context.Context, deps plugin.Deps, w plugin.Workload) error {
	_, prevContainer, err := loadState(deps, w)
	if err != nil {
		return err
	}
	if prevContainer == nil {
		return nil
	}

	// Proxy first so traffic stops landing on a container that is
	// about to disappear.
	if prevContainer.ProxyRouteID != "" {
		if err := deps.Proxy.DeleteRoute(ctx, prevContainer.ProxyRouteID); err != nil {
			slog.Warn("dockerfile: failed to remove proxy route", "workload", w.Name, "error", err)
		}
	}

	if prevContainer.ContainerID != "" {
		if err := deps.Docker.RemoveContainer(ctx, prevContainer.ContainerID, true); err != nil {
			slog.Warn("dockerfile: failed to remove container", "workload", w.Name, "error", err)
		}
	}

	if err := deps.Store.DeleteContainer(prevContainer.ID); err != nil && !errors.Is(err, store.ErrNotFound) {
		slog.Warn("dockerfile: failed to delete container row", "workload", w.Name, "error", err)
	}
	// The per-workload save-mutex is reference-counted (see state.go) and
	// frees itself when the last holder releases, so teardown no longer
	// deletes it explicitly — doing so could race a concurrent saveState
	// and break the RMW serialization the lock provides.
	return nil
}
