<?php

namespace App\Service;

use Symfony\Contracts\HttpClient\HttpClientInterface;
use Symfony\Component\DependencyInjection\Attribute\Autowire;
use Symfony\Component\Filesystem\Filesystem;

class DiscordWebhookService
{
    public function __construct(
        private HttpClientInterface $client,
        #[Autowire('%env(DISCORD_WEBHOOK_URL)%')]
        private string $webhookUrl,
        #[Autowire('%kernel.project_dir%')]
        private string $projectDir,
    ) {
    }

    public function send(?string $content = null, array $embeds = []): void
    {
        if (empty($content) && empty($embeds)) {
            return;
        }

        $payload = [];
        if ($content) {
            $payload['content'] = $content;
        }
        if (!empty($embeds)) {
            $payload['embeds'] = $embeds;
        }

        try {
            $response = $this->client->request('POST', $this->webhookUrl, [
                'json' => $payload,
            ]);

            // Ensure the request was successful
            // This will throw an exception if the status code is not 2xx
            // providing we access headers/content or call getContent()
            // However, simply calling request() is lazy.
            // We force it by getting the status code.
            $statusCode = $response->getStatusCode();
            
            if ($statusCode < 200 || $statusCode >= 300) {
                 throw new \RuntimeException(sprintf('Discord Webhook failed with status code %d', $statusCode));
            }

        } catch (\Throwable $e) {
            $this->handleError($content ?? 'Embed Message', $e);
        }
    }

    private function handleError(string $content, \Throwable $exception): void
    {
        $filesystem = new Filesystem();
        $logDir = $this->projectDir . '/var/log';
        if (!$filesystem->exists($logDir)) {
            $filesystem->mkdir($logDir);
        }

        $filename = sprintf('%s/discord_webhook_error_%s.json', $logDir, date('Ymd_His'));
        
        $data = [
            'timestamp' => date('c'),
            'content' => $content,
            'error' => $exception->getMessage(),
            'trace' => $exception->getTraceAsString(),
        ];

        file_put_contents($filename, json_encode($data, JSON_PRETTY_PRINT));
    }
}
