package service

import (
	"net/http"

	"cmr-backend/internal/apperr"
	"cmr-backend/internal/store/postgres"
)

const (
	launchReadyReasonOK                  = "event is active and launchable"
	launchReadyReasonNotActive           = "event is not active"
	launchReadyReasonReleaseMissing      = "event does not have a published release"
	launchReadyReasonRuntimeMissing      = "current published release is missing runtime binding"
	launchReadyReasonPresentationMissing = "current published release is missing presentation binding"
	launchReadyReasonContentMissing      = "current published release is missing content bundle binding"
)

func evaluateEventLaunchReadiness(event *postgres.Event) (bool, string) {
	if event == nil {
		return false, launchReadyReasonReleaseMissing
	}
	if event.Status != "active" {
		return false, launchReadyReasonNotActive
	}
	if event.CurrentReleaseID == nil || event.CurrentReleasePubID == nil || event.ConfigLabel == nil || event.ManifestURL == nil {
		return false, launchReadyReasonReleaseMissing
	}
	if buildRuntimeSummaryFromEvent(event) == nil {
		return false, launchReadyReasonRuntimeMissing
	}
	if buildPresentationSummaryFromEvent(event) == nil {
		return false, launchReadyReasonPresentationMissing
	}
	if buildContentBundleSummaryFromEvent(event) == nil {
		return false, launchReadyReasonContentMissing
	}
	return true, launchReadyReasonOK
}

func launchReadinessError(reason string) error {
	switch reason {
	case launchReadyReasonNotActive:
		return apperr.New(http.StatusConflict, "event_not_launchable", reason)
	case launchReadyReasonReleaseMissing:
		return apperr.New(http.StatusConflict, "event_release_missing", reason)
	case launchReadyReasonRuntimeMissing:
		return apperr.New(http.StatusConflict, "event_release_runtime_missing", reason)
	case launchReadyReasonPresentationMissing:
		return apperr.New(http.StatusConflict, "event_release_presentation_missing", reason)
	case launchReadyReasonContentMissing:
		return apperr.New(http.StatusConflict, "event_release_content_bundle_missing", reason)
	default:
		return apperr.New(http.StatusConflict, "event_not_launchable", reason)
	}
}
