package k8scalendar

import (
	"crypto/sha256"
	"encoding/hex"
	"fmt"
	"time"
)

const (
	CloudEKS = "EKS"
	CloudGKE = "GKE"

	ReleasePrecisionDay     = "day"
	ReleasePrecisionMonth   = "month"
	ReleasePrecisionQuarter = "quarter"
)

// ReleasePrecisionReadyForEvents reports whether lifecycle dates are exact enough to notify.
func ReleasePrecisionReadyForEvents(precision string) bool {
	return precision == ReleasePrecisionDay
}

func CloudToProvider(cloud string) string {
	switch cloud {
	case CloudEKS:
		return "aws"
	case CloudGKE:
		return "gcp"
	default:
		return ""
	}
}

type VersionLifecycle struct {
	ID                            uint64     `json:"id"`
	Cloud                         string     `json:"cloud"`
	Version                       string     `json:"version"`
	CloudProvider                 string     `json:"cloud_provider"`
	LifecycleStart                time.Time  `json:"lifecycle_start"`
	EndOfStandardSupport          time.Time  `json:"end_of_standard_support"`
	EndOfExtendedSupport          *time.Time `json:"end_of_extended_support,omitempty"`
	ReleasePrecision              string     `json:"release_precision"`
	SourceURL                     string     `json:"source_url"`
	Fingerprint                   string     `json:"fingerprint"`
	ScrapedAt                     time.Time  `json:"scraped_at"`
	NotifiedVersionAddedAt        *time.Time `json:"notified_version_added_at,omitempty"`
	NotifiedEOSChangedFingerprint string     `json:"notified_eos_changed_fingerprint,omitempty"`
	EOSApproachingNotifiedFor     *time.Time `json:"eos_approaching_notified_for,omitempty"`
}

func (v *VersionLifecycle) ComputeFingerprint() string {
	ext := ""
	if v.EndOfExtendedSupport != nil {
		ext = v.EndOfExtendedSupport.Format(time.RFC3339)
	}
	raw := fmt.Sprintf("%s|%s|%s|%s|%s|%s",
		v.Cloud, v.Version,
		v.LifecycleStart.Format(time.RFC3339),
		v.EndOfStandardSupport.Format(time.RFC3339),
		ext, v.ReleasePrecision)
	sum := sha256.Sum256([]byte(raw))
	return hex.EncodeToString(sum[:])
}
