<?php

namespace App\Services;

use App\Models\NewsCategory;
use Illuminate\Contracts\Pagination\LengthAwarePaginator;
use App\Exceptions\ApiHttpException;
use App\Libs\Api\ParsedListParams;
use Illuminate\Database\Eloquent\Builder;
use App\Services\DataService;

class NewsCategoryDataService extends DataService
{
    /**
     * Gets and filters news categories
     *
     * @param ParsedListParams $params - Filter and order data
     * @return Illuminate\Contracts\Pagination\LengthAwarePaginator
     */
    public function list(ParsedListParams $params): LengthAwarePaginator
    {
        /** @var Builder $query */
        $query = NewsCategory::full();
        //check if the default filters are to be applied
        $this->applyDefaultFilters($query, $params);
        $this->applyQueryParams($query, $params);
        return $query->paginate($params->itemsPerPage, ['*'], 'page', $params->pageNumber);
    }


    /**
     * Finds a single model for the news category
     *
     * @param int $id
     * @throws ApiHttpException if the provided News Category record is not found.
     * @return NewsCategory
     */
    public function find(int $id): NewsCategory
    {
        $category = NewsCategory::find($id);
        if (!$category) {
            throw new ApiHttpException(404, 'item_not_found');
        }

        return $category;
    }


    /**
     * applyQueryParams
     *
     * @param Builder &$query
     * @param ParsedListParams $params
     * @return void
     */
    private function applyQueryParams(Builder $query, ParsedListParams $params): void
    {

        $orderDirection = $params->orderDirection;
        $orderBy        = $params->orderBy;
        if ($orderBy === 'name') {
            $orderBy = 'title';
        }
        $query->orderBy($orderBy, $orderDirection);

        // Apply the specific Filters
        // News Category name Filter
        if (isset($params->filters['name'])) {
            $query->where('title', 'like', $params->filters['name'] . '%');
        }
    }
}
