<?php

declare(strict_types=1);

namespace Stream\Infrastructure\Service;

use Core\General\Helper\DateTimeHelper;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\GuzzleException;
use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
use Symfony\Component\HttpKernel\Exception\HttpException;

class YammatStreamManager
{
    private Client $client;

    public function __construct(
        private readonly ParameterBagInterface $parameters,
    ) {
        $this->client = new Client([
            'base_uri' => $parameters->get('yammat.base_url'),
            'timeout' => 0,
            'headers' => [
                'X-api-key' => $this->parameters->get('yammat.api_key'),
                'Connection' => 'keep-alive',
                'Accept-Encoding' => 'gzip, deflate, br',
            ],
        ]);
    }

    /**
     * @return list<array<string, mixed>>
     */
    public function fetchFilesList(): array
    {
        try {
            $response = $this->client->request(
                'GET',
                'station/test/files/list',
                [
                    'query' => [
                        'currentDirectory' => 'recordings',
                        'flushCache' => 'false',
                    ],
                ],
            );

            $body = $response->getBody();
            /** @var array<string|int, mixed> $audioFilesData */
            $audioFilesData = json_decode((string) $body, true);
            $audioFiles = [];

            foreach ($audioFilesData as $audioFile) {
                $startTimestamp = new \DateTime();
                $startTimestamp->setTimestamp($audioFile['timestamp']);

                if ($audioFile['type'] === 'media') {
                    $audioFiles[] = [
                        'id' => $audioFile['media']['id'],
                        'title' => $audioFile['path_short'],
                        'length' => $audioFile['media']['length'],
                        'start' => $startTimestamp,
                        'file_link' => $audioFile['media']['links']['self'],
                        'play_link' => $audioFile['media']['links']['play'],
                        'download_link' => \sprintf('%s%s', 'https://stream.yammat.fm', $audioFile['links']['download']),
                        'art' => $audioFile['media']['links']['art'],
                    ];
                }
            }
        } catch (GuzzleException|\Exception $e) {
            throw new HttpException($e->getCode(), $e->getMessage());
        }

        return $audioFiles;
    }

    /**
     * @return list<array<string, mixed>>
     */
    public function fetchSchedule(): array
    {
        $startDateTime = new \DateTime();
        $startDateTime->modify('-1 hours');
        $startDateTime = $startDateTime->format(DateTimeHelper::YMD);

        $endDateTime = new \DateTime();
        $endDateTime = $endDateTime->format(DateTimeHelper::YMD);

        try {
            $response = $this->client->request(
                'GET',
                'station/test/history',
                [
                    'query' => [
                        'start' => $startDateTime,
                        'end' => $endDateTime,
                    ],
                ],
            );

            /** @var array<string|int, mixed> $scheduleData */
            $scheduleData = json_decode((string) $response->getBody(), true);
            $schedule = [];

            foreach ($scheduleData as $song) {
                $startTimestamp = new \DateTime();
                $startTimestamp->setTimestamp($song['played_at']);

                $schedule[] = [
                    'id' => $song['sh_id'],
                    'start' => $startTimestamp->format(DateTimeHelper::ISO8601),
                    'duration' => $song['duration'],
                    'art' => $song['song']['art'],
                    'text' => $song['song']['text'],
                    'artist' => $song['song']['artist'],
                    'title' => $song['song']['title'],
                ];
            }
        } catch (GuzzleException|\Exception $e) {
            throw new HttpException($e->getCode(), $e->getMessage());
        }

        return $schedule;
    }
}
