import {
  k8sPatch,
  k8sGet,
  K8sResourceCommon,
  K8sModel
} from '@openshift-console/dynamic-plugin-sdk';

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

const namespaceModel: K8sModel = {
  apiVersion: 'v1',
  kind: 'Namespace',
  plural: 'namespaces',
  abbr: 'NS',
  label: 'Namespace',
  labelPlural: 'Namespaces',
};

const projectPauseModel: K8sModel = {
  apiVersion: 'projectpause.openshift.io/v1alpha1',
  kind: 'ProjectPauseConfig',
  plural: 'projectpauseconfigs',
  abbr: 'PPC',
  label: 'Project Pause Config',
  labelPlural: 'Project Pause Configs',
};

export const DEFAULT_OPERATOR_CONFIG: ProjectOperatorConfig = {
  apiVersion: projectPauseModel.apiVersion,
  kind: projectPauseModel.kind,
  name: 'project-pause-operator-config',
  namespace: 'openshift-operators',
};

type OperatorStatus = K8sResourceCommon & {
  status?: {
    ready?: boolean;
  };
};

export const getOperatorStatus = async (namespace: string): Promise<boolean> => {
  try {
    const response = await k8sGet<OperatorStatus>({
      model: projectPauseModel,
      name: DEFAULT_OPERATOR_CONFIG.name,
    });

    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 patch = [
    {
      op: 'add',
      path: '/metadata/annotations/project-pause-operator.openshift.io~1paused',
      value: isPaused ? 'true' : 'false',
    },
  ];

  await k8sPatch({
    model: namespaceModel,
    resource: { metadata: { name: namespace } } as K8sResourceCommon,
    data: patch,
  });
};

export const getProjectPauseState = async (
  namespace: string,
): Promise<{ isPaused: boolean; isOperatorReady: boolean }> => {
  try {
    const [namespaceResource, operatorReady] = await Promise.all([
      k8sGet<K8sResourceCommon>({
        model: namespaceModel,
        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,
    };
  }
}; 