<?php

return [
  'pattern' => '(:all)toggle-favorite.json',
  'method' => 'post',
  'action'  => function () {
      $json = file_get_contents('php://input');
      $data = json_decode($json);

      $fileName = $data->fileName;

      $page = page($data->inspirationUri);
      $file = $page->files()->find($fileName);
      
      $user = Find::user($data->userUuid);
      $favoriteForUsers = $file->favoriteForUsers()->toUsers();

      $action = null;

      if ($favoriteForUsers->has($user)) {
        $favoriteForUsers->remove($user);
        $action = 'retirée des';
      } else {
        $favoriteForUsers->add($user);
        $action = 'ajoutée aux';
      }

      $array = $favoriteForUsers->toArray();
      $yaml = Data::encode($array, 'yaml');

      $newFile = $file->update([
        'favoriteForUsers' => $yaml
      ]);
      
      return json_encode($newFile->favoriteForUsers()->value());
  }
];