<?php

namespace App\Services;

use App\Models\Share;
use App\Models\User;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;

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

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

    /**
     * Get request user's posts shared
     *
     * @param User $user
     * @param int|null $pageNumber
     * @return array
     */
    public static function userSharedPosts(User $user, int $pageNumber = null): array
    {
        $queryBuilder = Share::query()->with('currentPost')->where("user_id", $user->{"id"})->orderByDesc("created_at");
        $sharedPostPaginator = $queryBuilder->paginate(
            perPage: config("torryme.constants.items_per_page"),
            page: $pageNumber
        );

        $sharedPostArray = array();
        foreach ($sharedPostPaginator as $sharedPost) {
            $post = $sharedPost->{"currentPost"};

            $sharedPostArray[] = $post->commonSerialization();
        }

        return default_paginator_format(
            $sharedPostPaginator->lastPage(),
            $sharedPostPaginator->total(),
            $sharedPostPaginator->currentPage(),
            "posts",
            $sharedPostArray,
        );
    }

    /**
     * Check user already shared post
     *
     * @param User $user
     * @param int $postId
     * @return bool
     */
    public static function alreadySharedPost(User $user, int $postId): bool
    {
        //Query table
        return
            Share::query()
                ->where("user_id", $user->{"id"})
                ->where("post_id", $postId)
                ->exists();
    }
}
