<?php

namespace App\Services\Settings\History;

use App\Models\ApiRequestHistory;
use App\Repositories\CommonFilterRepository;
use App\Http\Responses\ReportOutputData;

class ApiRequestHistoryService
{
    /**
     * Constructs a new instance of the class.
     *
     * @param CommonFilterRepository $commonFilterRepository The common filter repository.
     * @param ReportOutputData $reportOutputData The report output data.
     */
    public function __construct(
        protected CommonFilterRepository $commonFilterRepository,
        protected ReportOutputData $reportOutputData
    ) {}

    /**
     * Retrieves data from the API histories and returns it along with the count.
     *
     * @return array Returns an associative array with 'apiHistories' and 'count' keys.
     */
    public function data()
    {
        $apiHistories = ApiRequestHistory::with('client');
        $apiHistories = $this->filterWithInputData($apiHistories);
        $count  = $apiHistories->count();
        $apiHistories = $this->reportOutputData->getOutputData($apiHistories, ['created_at' => 'asc']);

        return compact('apiHistories', 'count');
    }

    /**
     * Filter apiHistories based on input data.
     *
     * @param $apiHistories
     *
     * @return mixed
     */
    public function filterWithInputData($apiHistories)
    {
        $requestedData = request('form');
        $apiHistories = $this->commonFilterRepository->filterWithDirectDateRange($apiHistories, 'created_at', $requestedData['date_from'], $requestedData['date_to']);

        return $apiHistories;
    }

    /**
     * Get data for report.
     *
     * @param $apiRequestHistories
     * @param $start
     * @param $data
     *
     * @return array
     */
    public function getApiRequestData($apiRequestHistories, $start, $data)
    {
        $parentIndex = $start;

        foreach ($apiRequestHistories as $apiRequestHistory) {
            $parentIndex++;
            $nestedData = $this->getNestedData($apiRequestHistory, $parentIndex);
            $data[] = $nestedData;
        }

        return $data;
    }

    /**
     * Get nested data for report.
     *
     * @param $apiRequestHistory
     * @param $index
     *
     * @return array
     */
    public function getNestedData($apiRequestHistory, $index)
    {
        $nestedData['index'] = $index;
        $nestedData['name'] = $apiRequestHistory->client->name ?? '';
        $nestedData['api_endpoint'] = $apiRequestHistory->api_url ?? '';
        $nestedData['ip'] = $apiRequestHistory->request_ip ?? '';
        $nestedData['method'] = $apiRequestHistory->request_method ?? '';
        $nestedData['date'] = $apiRequestHistory->created_date ?? '';

        return $nestedData;
    }
}
