<?php

namespace App\Services;

use App\Models\MessageViewHistory;
use App\Models\RealtimeMessage;
use App\Models\User;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;

trait MessageViewHistoryService
{
   /**
    * Store new record
    *
    * @param array $data
    * @return Builder|Model
    */
   public static function store(array $data): Model|Builder
   {
      return MessageViewHistory::query()->create($data);
   }

   /**
    * Serialize for channel
    *
    * @return array
    */
   public function serializeForChannel(): array
   {
      return array(
         'participant_user_id' => $this->{'participant'}->{'participant_id'},
         'seen_at' => $this->{'seen_at'},
      );
   }

   /**
    * Last message delivery
    *
    * @param RealtimeMessage $message
    * @param User $user
    * @return Builder|Model|null
    */
   public static function lastMessageViews(RealtimeMessage $message, User $user): Model|Builder|null
   {
      return
         MessageViewHistory::query()
            ->where('message_id', $message->{'id'})
            ->whereHas('participant.user', function (Builder $builder) use ($user) {
               $builder->where('id', $user->{'id'});
            })
            ->latest()
            ->first();
   }

   /**
    * Message views history
    *
    * @param RealtimeMessage $message
    * @return array
    */
   public static function messageViewsHistory(RealtimeMessage $message): array
   {
      $histories = MessageViewHistory::query()->where('message_id', $message->{'id'})->latest()->get();
      $result = [];

      foreach ($histories as $history) {
         $result[] = $history->serializeForChannel();
      }

      return $result;
   }
}
