<?php

declare(strict_types=1);

namespace App\Controller;

use App\DependencyInjection\JsonEnvVarLoader;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\KernelInterface;
use Symfony\Component\Routing\Attribute\Route;

class EnvDataController extends AbstractController
{
    private const string ENV_VARS_FILE = 'env.json';

    public function __construct(
        private readonly KernelInterface $kernel

    )
    {
    }

    #[Route('/env-vars', methods: ['GET'])]
    public function getEnvVars(): JsonResponse
    {
        $projectDir = $this->kernel->getProjectDir();

        $fileName = $projectDir . DIRECTORY_SEPARATOR . self::ENV_VARS_FILE;
        if (!is_file($fileName)) {
            throw new \RuntimeException('File not found: '.$fileName);
        }

        $content = json_decode(file_get_contents($fileName), true);

        return new JsonResponse(['vars' => $content['vars']]);
    }

    #[Route('/env-vars', methods: ['POST'])]
    public function updateEnvVars(Request $request): JsonResponse
    {
        $data = json_decode($request->getContent(), true);
        $projectDir = $this->kernel->getProjectDir();

        $fileName = $projectDir . DIRECTORY_SEPARATOR . self::ENV_VARS_FILE;

        if (!isset($data['vars']) || !is_array($data['vars'])) {
            return new JsonResponse(['error' => 'Invalid payload'], Response::HTTP_BAD_REQUEST);
        }

        $json = json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);

        if ($json === false) {
            throw new \RuntimeException('Failed to encode JSON: ' . json_last_error_msg());
        }

        if (file_put_contents($fileName, $json) === false) {
            throw new \RuntimeException('Failed to write to file: ' . self::ENV_VARS_FILE);
        }

        return new JsonResponse(['message' => 'Variables updated successfully']);
    }
}
