<?php declare(strict_types=1);

namespace App\Engine\Files\FilesJs\Controllers;

final class SaveTextController extends BaseFileManagerController
{

    public function index(\Symfony\Component\HttpFoundation\Request $request): \Symfony\Component\HttpFoundation\JsonResponse
    {
        $data = json_decode($request->getContent(), true);

        $folderPath = $this->sanitizePath($data['folderPath'] ?? '');
        $fileName = basename($data['fileName'] ?? '');
        $text = $data['text'] ?? '';

        $itemPath = $this->basePath . '/' . trim($folderPath . '/' . $fileName, '/');
        if (!$this->isPathInsideBase($itemPath)) {
            return new \Symfony\Component\HttpFoundation\JsonResponse([
                'error' => 'Invalid path.'
            ], 400);
        }

        try {
            $bytesWritten = file_put_contents($itemPath, $text);
            if ($bytesWritten === false) {
                return new \Symfony\Component\HttpFoundation\JsonResponse([
                    'error' => 'Failed to save the file.'
                ], 500);
            }
        } catch (\Throwable $e) {
            return new \Symfony\Component\HttpFoundation\JsonResponse([
                'error' => 'Failed to save the file.'
            ], 500);
        }

        return new \Symfony\Component\HttpFoundation\JsonResponse([
            'message' => 'File saved successfully.'
        ]);
    }

}