<?php

namespace Eater\Glim\Handler\Panel\Servers;

use Eater\Glim\Handler\Session;
use Eater\Glim\Model\ServerQuery;
use Eater\Glim\Service\CA;
use Eater\Glim\Service\Server;
use Symfony\Component\Config\Definition\Exception\Exception;

class Sign extends Session
{
    protected $shouldHaveSuperuser = true;
    
    public function handle()
    {
        /** @var CA $ca */
        $ca = $this->get('ca');
        $server = ServerQuery::create()->findOneByFingerprint($this->post('fingerprint'));

        /** @var Server $serverManager */
        $serverManager = $this->get('server');
        try {
            $csr = $serverManager->getCsrFromServer($server);
            $crt = $ca->signServerKey($csr, $server->getFqdn());
        } catch (\Exception $e) {
            return $this->json([
                'success' => false,
                'error' => $e->getMessage()
            ]);
        }

        $server->setCertificate($crt);
        $server->save();

        try {
            $serverManager->deliverSignedCertificate($server);
        } catch (\Exception $e) {
            return $this->json([
                'success' => false,
                'error' => 'Failed to deliver certificate to server: ' . $e->__toString()
            ]);
        }
        
        return $this->json([
            'success' => true
        ]);
    }
}