<?php

namespace App\Services;

abstract class BaseService
{
    /**
     * Normalize pagination options
     * 
     * @return array
     * 
     * @param array $options
     * @param int $defaultLimit
     * @param int $maxLimit
     * 
     * @throws Exception
     */
    protected function normalizePagination(
        array $options = [],
        int $defaultLimit = 50,
        int $maxLimit = 100
    ): array {
        $offset = (int)($options['offset'] ?? 0);
        $limit  = (int)($options['limit']  ?? $defaultLimit);

        if ($offset < 0) $offset = 0;
        if ($limit < 1) $limit = 1;
        if ($limit > $maxLimit) $limit = $maxLimit;

        return compact('offset', 'limit');
    }

    /**
     * Validate params
     * 
     * @throws Exception
     * 
     * @param array $params
     * 
     * @return void
     */
    protected function validateParams(array $params): void
    {
        if (!empty($params['filterBy'])) {
            foreach ($params['filterBy'] as $filter) {
                if (
                    !isset($filter['field']) ||
                    !isset($filter['operator']) ||
                    !array_key_exists('value', $filter)
                ) {
                    throw new \InvalidArgumentException('INVALID_FILTER_FORMAT');
                }
            }
        }

        if (!empty($params['orderBy'])) {
            foreach ($params['orderBy'] as $order) {
                if (!isset($order['field'], $order['direction'])) {
                    throw new \InvalidArgumentException('INVALID_ORDER_FORMAT');
                }
            }
        }

        if (!empty($params['fields']) && !is_array($params['fields'])) {
            throw new \InvalidArgumentException('INVALID_FIELDS_FORMAT');
        }
    }
}
