<?php

use adrienpayet\comments\Comment;

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

      // kirby()->impersonate('kirby');

      $page = page($data->fileParentUri);
      $project = $page->parent()->template() == 'project' ? $page->parent() : $page->parent()->parent();
      $file = $page->file($data->fileName);
      $user = kirby()->user($data->userUuid);


      $comments = $file->comments()->isEmpty() == true ? [] : Yaml::decode($file->comments()->value());

      foreach ($comments as $existingComment) {
          if
          (
              $existingComment['author']['email'] == $user->email() &&
              $existingComment['text'] == $data->text &&
              $existingComment['position']['x'] == $data->position->x &&
              $existingComment['position']['y'] == $data->position->y
          ) {
              return json_encode(null);
          }
      }

      $commentData = [
        'location' => [
          'page'    => $page,
          'project' => $project,
          'file'    => $file,
        ],
        'position' => [
          'x' => $data->position->x,
          'y' => $data->position->y,
        ],
        'date'   => (string) $data->date,
        'text'   => $data->text,
        'author' => kirby()->user(),
        'id'     => Str::uuid(),
        'type'   => 'comment',
      ];

      if (isset($data->position->pageIndex)) {
          $commentData['position']['pageIndex'] = $data->position->pageIndex;
      }

      $newComment = new Comment($commentData);

      $comments[] = $newComment->toArray();

      $newFile = $file->update([
        'comments' => $comments,
      ]);

      echo json_encode(getFileData($newFile));

      try {
          $project->createNotification($commentData);
      } catch (\Throwable $th) {
          throw new Exception($th->getMessage() . '. line ' . $th->getLine() . ' in file ' . $th->getFile(), 1);
      }

      exit;
  },
];
