<?php declare(strict_types=1);

namespace App\Engine\Files\FilesJs\Controllers;

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

        $currentItemPath = $this->basePath . '/' . trim($folderPath . '/' . $currentName, '/');
        $newItemPath = $this->basePath . '/' . trim($folderPath . '/' . $newName, '/');

        if (!$this->isPathInsideBase($currentItemPath) || !$this->isPathInsideBase($newItemPath)) {
            return new \Symfony\Component\HttpFoundation\JsonResponse([
                'error' => 'Invalid path.'
            ], 400);
        }

        if (!file_exists($currentItemPath)) {
            return new \Symfony\Component\HttpFoundation\JsonResponse([
                'error' => 'Item does not exist.'
            ], 400);
        }

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

        try {
            rename($currentItemPath, $newItemPath);
        } catch (\Throwable $e) {
            return new \Symfony\Component\HttpFoundation\JsonResponse([
                'error' => 'Something went wrong.'
            ], 500);
        }

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

}