export const DEPLOYMENT_STATES = Object.freeze([
  'checking', 'backup_pending', 'backup_running', 'backup_verified',
  'deploy_requested', 'deploy_running', 'health_wait',
  'succeeded', 'failed', 'rollback_required',
]);

export const ACTIVE_DEPLOYMENT_STATES = Object.freeze([
  'checking', 'backup_pending', 'backup_running', 'backup_verified',
  'deploy_requested', 'deploy_running', 'health_wait', 'rollback_required',
]);

const TRANSITION_ENTRIES = Object.freeze({
  checking: ['backup_pending', 'deploy_requested', 'failed'],
  backup_pending: ['backup_running', 'failed'],
  backup_running: ['backup_verified', 'failed'],
  backup_verified: ['deploy_requested', 'failed'],
  deploy_requested: ['deploy_running', 'health_wait', 'failed', 'rollback_required'],
  deploy_running: ['health_wait', 'succeeded', 'failed', 'rollback_required'],
  health_wait: ['succeeded', 'failed', 'rollback_required'],
  rollback_required: ['failed'],
  succeeded: [],
  failed: [],
});

export const DEPLOYMENT_TRANSITIONS = Object.freeze(Object.fromEntries(
  Object.entries(TRANSITION_ENTRIES).map(([state, targets]) => [state, Object.freeze([...targets])]),
));

const ACTIVE_SET = new Set(ACTIVE_DEPLOYMENT_STATES);

export function isDeploymentState(state) {
  return DEPLOYMENT_STATES.includes(state);
}

export function isActiveDeploymentState(state) {
  return ACTIVE_SET.has(state);
}

export function canTransitionDeployment(from, to) {
  return from === to || Boolean(DEPLOYMENT_TRANSITIONS[from]?.includes(to));
}
