<?php

namespace App\Services;

use App\Enums\GenericStatusEnum;
use App\Models\Community;
use App\Models\CommunitySetting;
use App\Models\User;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;

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

   /**
    * Update existing record
    *
    * @param array $data
    * @return mixed
    */
   public function updateService(array $data): mixed
   {
      return tap($this)->update($data);
   }

   /**
    * Create or update community setting s
    *
    * @param Community $community
    * @param array $data
    * @return Builder|Model
    */
   public static function createOrUpdateSetting(Community $community, array $data): Model|Builder
   {
      /** @var User $user */
      $user = auth()->user();

      /** @var CommunitySetting $communitySetting */
      $communitySetting = self::findByCommunityAndUser(
         $community->{'id'},
         $user->{'id'},
      );

      $enableNotification = $data['enable_notification'] ?? null;

      if($communitySetting != null) {
         $result = $communitySetting->editSetting($data);
      } else {
         $result = self::store([
            "enable_notification" => filled($enableNotification) ? $enableNotification : GenericStatusEnum::enable,
            "community_id" => $community->{'id'},
            "user_id" =>  $user->{"id"},
         ]);
      }

      return $result->refresh();
   }

   /**
    * Find by community id
    *
    * @param int $communityId
    * @param int $userId
    * @return Model|Builder|null
    */
   public static function findByCommunityAndUser(int $communityId, int $userId): Model|Builder|null
   {
      return
         CommunitySetting::query()
            ->where('community_id', $communityId)
            ->where('user_id', $userId)
            ->first();
   }

   /**
    * Edit community setting
    *
    * @param array $data
    * @return CommunitySetting
    */
   public function editSetting(array $data): CommunitySetting
   {
      $storeData = [];
      $enableNotification = $data['enable_notification'] ?? null;

      if(filled($enableNotification)) {
         $storeData['enable_notification'] = $enableNotification;
      }

      return $this->updateService($storeData);
   }
}
