<?php

namespace App\Controller\OgRepository\Git;

use App\Controller\OgRepository\AbstractOgRepositoryController;
use App\Dto\Input\CreateBackupInput;
use App\Entity\ImageRepository;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Attribute\AsController;
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;

#[AsController]
class CreateBackupAction extends AbstractOgRepositoryController
{
    public function __invoke(ImageRepository $repository, CreateBackupInput $input): JsonResponse
    {
        $content = $this->createRequest('POST', 'http://'.$repository->getIp().':8006/ogrepository/v1/git/repositories/'.$input->repository.'/backup', [
            'json' => [
                'ssh_server' => $input->sshServer,
                'ssh_user' => $input->sshUser,
                'ssh_port' => $input->sshPort,
                'filename' => $input->filename,
            ]
        ]);

        if (isset($content['error']) && $content['code'] === Response::HTTP_INTERNAL_SERVER_ERROR) {
            throw new BadRequestHttpException('Error creating backup');
        }

        return new JsonResponse(data: [], status: Response::HTTP_OK);
    }
}