import 'package:p_tits_pas/models/assistante_maternelle_model.dart';

/// Places disponibles attendues : capacité max − enfants rattachés.
int? amExpectedPlacesAvailable({
  required int? maxChildren,
  required int childrenCount,
}) {
  if (maxChildren == null) return null;
  return (maxChildren - childrenCount).clamp(0, maxChildren);
}

/// True s'il reste au moins une place d'accueil (capacité − enfants).
bool amHasFreePlace(AssistanteMaternelleModel am) {
  final expected = amExpectedPlacesAvailable(
    maxChildren: am.maxChildren,
    childrenCount: am.children.length,
  );
  if (expected != null) return expected > 0;
  final places = am.placesAvailable;
  if (places != null) return places > 0;
  return true;
}

/// True si la valeur déclarée par l'AM ne correspond pas au calcul métier.
bool amHasPlacesInconsistency({
  required int? maxChildren,
  required int? placesAvailable,
  required int childrenCount,
}) {
  final expected = amExpectedPlacesAvailable(
    maxChildren: maxChildren,
    childrenCount: childrenCount,
  );
  if (expected == null) return false;
  if (placesAvailable == null) return childrenCount > (maxChildren ?? 0);
  return placesAvailable != expected;
}

String? amPlacesVigilanceMessage(AssistanteMaternelleModel am) {
  if (!amHasPlacesInconsistency(
    maxChildren: am.maxChildren,
    placesAvailable: am.placesAvailable,
    childrenCount: am.children.length,
  )) {
    return null;
  }
  final stored = am.placesAvailable;
  final expected = amExpectedPlacesAvailable(
    maxChildren: am.maxChildren,
    childrenCount: am.children.length,
  );
  final storedLabel = stored?.toString() ?? 'non renseigné';
  final expectedLabel = expected?.toString() ?? '–';
  return 'Point de vigilance : l\'AM déclare $storedLabel place(s) disponible(s), '
      'alors que capacité ${am.maxChildren ?? '–'} − '
      '${am.children.length} enfant(s) rattaché(s) = $expectedLabel.';
}
