<?php

namespace App\Services;

use App\Enums\GenericStatusEnum;
use App\Exceptions\InvalidGetCommunityReportAttempt;
use App\Models\Community;
use App\Models\CommunityReport;
use App\Models\CommunitySubscriber;
use App\Models\User;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;

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

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

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

      return self::store([
         'subject' => $data["subject"],
         'message' => $data["message"] ?? null,
         'community_id' => $community->{'id'},
         'user_id' => $user->{"id"},
      ]);
   }

   /**
    * Get community reports
    *
    * @param int $communityId
    * @param null $pageNumber
    * @return array
    * @throws InvalidGetCommunityReportAttempt
    */
   public static function getCommunityReports(int $communityId, $pageNumber = null): array
   {
      try {
         /** @var User $user */
         $user = auth()->user();

         // Check if action is performed by community admin
         $isCommunityAdmin = CommunitySubscriber::checkIsCommunityAdminOrAlreadySubscriber(GenericStatusEnum::enable->value, $user->{"id"}, $communityId);

         if (!$isCommunityAdmin != null) {
            throw new InvalidGetCommunityReportAttempt(__("errors.invalid_get_community_reports_attempt"));
         }

         $queryBuilder =
            CommunityReport::query()
               ->with('reporter.userDetail', 'reporter.business')
               ->where('community_id', $communityId)
               ->orderBy('created_at');

         $paginator = $queryBuilder->paginate(
            perPage: config("torryme.constants.items_per_page"),
            page: $pageNumber
         );

         $result =  default_paginator_format(
            $paginator->lastPage(),
            $paginator->total(),
            $paginator->currentPage(),
            'reports',
            $paginator->items(),
         );
      } catch (\Exception $exception) {
         log_debug($exception, 'CommunityReportService::getCommunityReports');
         throw $exception;
      }

      return $result;
   }

}
