const RADIANS_TO_DEGREES = 180 / Math.PI;
const DEGREES_TO_RADIANS = Math.PI / 180;

export function textureLayerDegreesToRadians(value: unknown): number {
  const degrees = Number(value);
  return Number.isFinite(degrees) ? degrees * DEGREES_TO_RADIANS : 0;
}

export function radiansToTextureLayerDegrees(value: unknown): number {
  const radians = Number(value);
  return Number.isFinite(radians) ? radians * RADIANS_TO_DEGREES : 0;
}

export function resolveTextureLayerRotationDegrees(
  currentDegreesInput: unknown,
  patch: Record<string, unknown> | null | undefined,
  initialDegreesInput: unknown = 0,
): number {
  const currentDegrees = Number(currentDegreesInput);
  const initialDegrees = Number(initialDegreesInput);
  let next = Number.isFinite(currentDegrees) ? currentDegrees : 0;

  if (patch?.resetTransform === true) {
    next = Number.isFinite(initialDegrees) ? initialDegrees : 0;
  }

  const absoluteRadians = typeof patch?.rotation === 'number'
    ? patch.rotation
    : (typeof patch?.rotationZ === 'number' ? patch.rotationZ : null);
  if (absoluteRadians !== null) next = radiansToTextureLayerDegrees(absoluteRadians);

  if (typeof patch?.rotationBy === 'number') {
    next += radiansToTextureLayerDegrees(patch.rotationBy);
  }

  return Number.isFinite(next) ? next : 0;
}
