<?php

namespace App\Controllers\Api\V1;

use App\Controllers\BaseController;
use App\Services\System\SystemUpdateService;

class SystemUpdateController extends BaseController
{
    private SystemUpdateService $updater;

    public function initController(\CodeIgniter\HTTP\RequestInterface $request, \CodeIgniter\HTTP\ResponseInterface $response, \Psr\Log\LoggerInterface $logger)
    {
        parent::initController($request, $response, $logger);
        $this->updater = new SystemUpdateService();
    }

    public function upload()
    {
        $user = $this->currentUser();

        $file = $this->request->getFile('package');
        if (! $file || ! $file->isValid()) {
            return $this->jsonError([['code' => 'FILE_MISSING', 'message' => 'Please attach a .zip update package.']], 422);
        }
        if (strtolower($file->getClientExtension()) !== 'zip') {
            return $this->jsonError([['code' => 'INVALID_FILE_TYPE', 'message' => 'The update package must be a .zip file.']], 422);
        }

        $originalName = $file->getClientName();
        $tempPath = $file->getTempName();

        try {
            $result = $this->updater->applyUpdate($tempPath, $originalName, $user->id);
        } catch (\InvalidArgumentException $e) {
            return $this->jsonError([['code' => 'INVALID_PACKAGE', 'message' => $e->getMessage()]], 422);
        } catch (\RuntimeException $e) {
            return $this->jsonError([['code' => 'UPDATE_FAILED', 'message' => $e->getMessage()]], 500);
        }

        return $this->jsonSuccess([
            'message'       => "Update applied — {$result['files_changed']} file(s) changed. A backup was taken automatically before applying.",
            'files_changed' => $result['files_changed'],
            'update_id'     => $result['update_id'],
        ], [], 201);
    }

    public function rollback(int $updateId)
    {
        $user = $this->currentUser();

        try {
            $this->updater->rollback($updateId, $user->id);
        } catch (\RuntimeException $e) {
            return $this->jsonError([['code' => 'ROLLBACK_FAILED', 'message' => $e->getMessage()]], 422);
        }

        return $this->jsonSuccess(['message' => 'Rolled back to the pre-update state.']);
    }

    public function history()
    {
        return $this->jsonSuccess(['updates' => $this->updater->history()]);
    }
}
