# SetReferenceUnit

## Permission Scope

unit

## Overview

SetReferenceUnit changes the reference unit for a UoM category to a different unit within the same category. When the reference unit changes, all conversion factors in the category are automatically recalculated relative to the new reference. The new reference unit's conversion factor becomes 1.0.

This command supports scenarios where business requirements change and a different unit becomes the standard for measurement.

## Business Rules

- Target unit must exist and belong to the specified category
- Target unit must be in the same category as the current reference unit
- Setting the current reference unit as reference returns success with no change
- When reference unit changes, the new reference unit's conversion factor becomes 1.0
- All other units' conversion factors are recalculated: `new_factor = old_factor / new_reference_old_factor`
- Historical conversion calculations are not affected (they used the factors at time of calculation)

## Process Flow

```mermaid
flowchart TD
    A[Receive set reference request] --> B{Unit exists?}
    B -->|No| C[Return error: unit not found]
    B -->|Yes| D{Unit in specified category?}
    D -->|No| E[Return error: unit not in category]
    D -->|Yes| F{Already reference unit?}
    F -->|Yes| G[Return success: no change needed]
    F -->|No| H[Get new unit's current factor]
    H --> I[Recalculate all unit factors]
    I --> J[Set new unit factor to 1.0]
    J --> K[Update category reference unit pointer]
    K --> L[Return updated category]
```

## External Dependencies

- None

## Error Scenarios

- **UNIT_NOT_FOUND**: Specified unit ID does not exist
- **UNIT_NOT_IN_CATEGORY**: Unit belongs to a different category than specified

## Test Cases

- throws when unit doesn't exist
- throws when unit is not in specified category
- returns category unchanged when unit is already reference
- changes reference unit and recalculates conversion factors
