// Copyright 2026 Microsoft Corporation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package deletion

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

	ocmerrors "github.com/openshift-online/ocm-sdk-go/errors"

	"github.com/Azure/ARO-HCP/backend/pkg/utils/controllerutils"
	"github.com/Azure/ARO-HCP/internal/api/coreapi"
	"github.com/Azure/ARO-HCP/internal/database/cosmosstorage/corecosmosstorage"
	"github.com/Azure/ARO-HCP/internal/database/cosmosstorage/cosmosstorageutils"
	"github.com/Azure/ARO-HCP/internal/database/informers/coreinformers"
	"github.com/Azure/ARO-HCP/internal/database/listers/corelisters"
	unionkubeapplierinformers "github.com/Azure/ARO-HCP/internal/database/unioninformers/kubeapplier"
	"github.com/Azure/ARO-HCP/internal/ocm"
	"github.com/Azure/ARO-HCP/internal/utils"
)

// nodePoolClusterServiceIDClearer clears ClusterServiceID after the
// cluster-service NodePool itself has been confirmed gone. This runs after the
// delete dispatch controller has already issued the delete request
// (ClusterServiceDeletionTimestamp is set). We poll cluster-service for the
// NodePool and, on 404, zero out the stored ClusterServiceID so downstream
// code knows the CS resource is fully gone.
type nodePoolClusterServiceIDClearer struct {
	nodePoolLister       corelisters.NodePoolLister
	resourcesDBClient    corecosmosstorage.ResourcesDBClient
	clusterServiceClient ocm.ClusterServiceClientSpec
}

var _ controllerutils.NodePoolSyncer = (*nodePoolClusterServiceIDClearer)(nil)

func NewNodePoolClusterServiceIDClearerController(
	resourcesDBClient corecosmosstorage.ResourcesDBClient,
	clusterServiceClient ocm.ClusterServiceClientSpec,
	informers coreinformers.BackendInformers,
	kubeApplierInformers *unionkubeapplierinformers.UnionKubeApplierInformers,
) controllerutils.Controller {
	_, nodePoolLister := informers.NodePools()
	syncer := &nodePoolClusterServiceIDClearer{
		nodePoolLister:       nodePoolLister,
		resourcesDBClient:    resourcesDBClient,
		clusterServiceClient: clusterServiceClient,
	}

	return controllerutils.NewNodePoolWatchingController(
		"NodePoolDeletionClusterServiceIDClearer",
		resourcesDBClient,
		informers,
		kubeApplierInformers,
		time.Minute,
		syncer,
	)
}

// NeedsWork reports whether this controller has unfinished business for the
// given NodePool: deletion has been started (DeletionTimestamp), the deleter
// has already issued the CS delete (ClusterServiceDeletionTimestamp), and a
// ClusterServiceID is still recorded that needs verification before clearing.
func (c *nodePoolClusterServiceIDClearer) NeedsWork(nodePool *coreapi.HCPOpenShiftClusterNodePool) bool {
	// TODO temporary check to skip the new deletion approach for NodePools that were created before the new approach was implemented.
	// This will be removed once all nodepools whose deletion was triggered before the new approach is fully rolled out have been
	// fully deleted in all ARO-HCP permanent environments, for all regions.
	if !nodePool.ServiceProviderProperties.UsesNewNodePoolDeletionApproach {
		return false
	}

	return nodePool.ServiceProviderProperties.DeletionTimestamp != nil &&
		nodePool.ServiceProviderProperties.ClusterServiceDeletionTimestamp != nil &&
		nodePool.ServiceProviderProperties.ClusterServiceID != nil && len(nodePool.ServiceProviderProperties.ClusterServiceID.String()) > 0
}

// SyncOnce reads the NodePool from cluster-service. If cluster-service reports
// 404, the deletion has finished and we zero out ClusterServiceID. Any other
// state means cluster-service is still draining the NodePool. We retry on the
// next sync.
func (c *nodePoolClusterServiceIDClearer) SyncOnce(ctx context.Context, key controllerutils.HCPNodePoolKey) error {
	logger := utils.LoggerFromContext(ctx)

	cachedNodePool, err := c.nodePoolLister.Get(ctx, key.SubscriptionID, key.ResourceGroupName, key.HCPClusterName, key.HCPNodePoolName)
	if cosmosstorageutils.IsNotFoundError(err) {
		return nil
	}
	if err != nil {
		return utils.TrackError(fmt.Errorf("failed to get node pool from cache: %w", err))
	}
	if !c.NeedsWork(cachedNodePool) {
		return nil
	}

	nodePoolCRUD := c.resourcesDBClient.HCPClusters(key.SubscriptionID, key.ResourceGroupName).NodePools(key.HCPClusterName)
	nodePool, err := nodePoolCRUD.Get(ctx, key.HCPNodePoolName)
	if cosmosstorageutils.IsNotFoundError(err) {
		return nil
	}
	if err != nil {
		return utils.TrackError(fmt.Errorf("failed to get node pool: %w", err))
	}
	if !c.NeedsWork(nodePool) {
		return nil
	}

	csID := nodePool.ServiceProviderProperties.ClusterServiceID
	_, err = c.clusterServiceClient.GetNodePool(ctx, *csID)
	if err != nil {
		var ocmError *ocmerrors.Error
		if !errors.As(err, &ocmError) || ocmError.Status() != http.StatusNotFound {
			return utils.TrackError(fmt.Errorf("failed to get cluster-service NodePool: %w", err))
		}
		// 404 - cluster-service has finished deleting the NodePool, clear the CS ID.
		logger.Info("cluster-service NodePool gone. Clearing ClusterServiceID", "clusterServiceID", csID.String())
		replacement := nodePool.DeepCopy()
		replacement.ServiceProviderProperties.ClusterServiceID = nil
		_, err = nodePoolCRUD.Replace(ctx, replacement, nil)
		if cosmosstorageutils.IsPreconditionFailedError(err) {
			// if we have a conflict error, then we're guaranteed that our informer will eventually see an update and trigger us again.
			return nil
		}
		if err != nil {
			return utils.TrackError(fmt.Errorf("failed to clear ClusterServiceID: %w", err))
		}
		return nil
	}

	// NodePool still exists in cluster-service. Nothing to do yet.
	return nil
}
