/// Crop-calendar months are stored compactly as a 12-bit mask in a single
/// nullable integer column (bit 0 = January … bit 11 = December). A phase can
/// happen in several months (e.g. sow lettuce in March, April and September),
/// so the calendar is a *set* of months, not one. `null` or `0` means "not
/// recorded". Pure functions — no I/O — so they are trivially testable.
library;

/// Packs a set of 1..12 month numbers into a bitmask, or null when empty (so an
/// unset phase stays null in the DB rather than 0). Values outside 1..12 are
/// ignored.
int? monthsToMask(Iterable<int> months) {
  var mask = 0;
  for (final m in months) {
    if (m >= 1 && m <= 12) mask |= 1 << (m - 1);
  }
  return mask == 0 ? null : mask;
}

/// Unpacks a month bitmask into an ascending list of 1..12 month numbers.
/// Returns an empty list for null or 0.
List<int> maskToMonths(int? mask) {
  if (mask == null || mask == 0) return const [];
  return [
    for (var m = 1; m <= 12; m++)
      if (mask & (1 << (m - 1)) != 0) m,
  ];
}

/// Whether month [month] (1..12) is set in [mask].
bool maskHasMonth(int? mask, int month) =>
    mask != null && month >= 1 && month <= 12 && mask & (1 << (month - 1)) != 0;

/// Toggles month [month] (1..12) in [mask], returning the new mask (null when
/// the result is empty).
int? toggleMonth(int? mask, int month) {
  if (month < 1 || month > 12) return mask;
  final next = (mask ?? 0) ^ (1 << (month - 1));
  return next == 0 ? null : next;
}
