<?php declare(strict_types=1);

namespace App\Engine\Files\FilesJs\Controllers;

final class CreateFolderController 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'] ?? '');
        $folderName = basename($data['folderName'] ?? '');

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

        if (file_exists($itemPath)) {
            return new \Symfony\Component\HttpFoundation\JsonResponse([
                'error' => 'Folder already exists.'
            ], 400);
        }

        try {
            mkdir($itemPath, 0777, true);
        } catch (\Throwable $e) {
            return new \Symfony\Component\HttpFoundation\JsonResponse([
                'error' => 'Error creating folder.'
            ], 500);
        }

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

}