import { k8sGetResource, k8sPatchResource, K8sResourceCommon } from '@openshift-console/dynamic-plugin-sdk';

export type ProjectOperatorConfig = {
  apiVersion: string;
  kind: string;
  name: string;
  namespace: string;
};

export const DEFAULT_OPERATOR_CONFIG: ProjectOperatorConfig = {
  apiVersion: 'projectpause.openshift.io/v1alpha1',
  kind: 'ProjectPauseConfig',
  name: 'project-pause-operator-config',
  namespace: 'openshift-operators',
};

export const getOperatorStatus = async (namespace: string): Promise<boolean> => {
  try {
    const response = await k8sGetResource({
      model: {
        apiVersion: DEFAULT_OPERATOR_CONFIG.apiVersion,
        kind: DEFAULT_OPERATOR_CONFIG.kind,
        plural: 'projectpauseconfigs',
      },
      queryOptions: {
        name: DEFAULT_OPERATOR_CONFIG.name,
        namespace: DEFAULT_OPERATOR_CONFIG.namespace,
      },
    });

    return response?.status?.ready === true;
  } catch (error) {
    console.error('Failed to get operator status:', error);
    return false;
  }
};

export const pauseProject = async (
  namespace: string,
  isPaused: boolean,
): Promise<void> => {
  const annotations = {
    'project-pause-operator.openshift.io/paused': isPaused ? 'true' : 'false',
  };

  await k8sPatchResource({
    model: {
      apiVersion: 'v1',
      kind: 'Namespace',
      plural: 'namespaces',
    },
    resource: { metadata: { name: namespace } } as K8sResourceCommon,
    data: [
      {
        op: 'add',
        path: '/metadata/annotations',
        value: annotations,
      },
    ],
  });
};

export const getProjectPauseState = async (
  namespace: string,
): Promise<{ isPaused: boolean; isOperatorReady: boolean }> => {
  try {
    const [namespaceResource, operatorReady] = await Promise.all([
      k8sGetResource({
        model: {
          apiVersion: 'v1',
          kind: 'Namespace',
          plural: 'namespaces',
        },
        queryOptions: {
          name: namespace,
        },
      }),
      getOperatorStatus(namespace),
    ]);

    const isPaused = namespaceResource?.metadata?.annotations?.['project-pause-operator.openshift.io/paused'] === 'true';

    return {
      isPaused,
      isOperatorReady: operatorReady,
    };
  } catch (error) {
    console.error('Failed to get project pause state:', error);
    return {
      isPaused: false,
      isOperatorReady: false,
    };
  }
}; 