<?php

namespace App\Apps\Versionmgr\Controllers;

use App\Apps\Versionmgr\Services\PackageService;
use App\Apps\Versionmgr\Services\UpgradeService;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;

class PackageController extends Controller
{
    protected PackageService $packageService;

    protected UpgradeService $upgradeService;

    public function __construct(PackageService $packageService, UpgradeService $upgradeService)
    {
        $this->packageService = $packageService;
        $this->upgradeService = $upgradeService;
    }

    public function index()
    {
        $current = \App\Apps\Versionmgr\Models\SystemVersion::getCurrentVersion();

        return view('versionmgr::package.index', [
            'currentVersion' => $current ? $current->version : '',
            'currentBuild' => $current ? $current->build : '',
        ]);
    }

    public function upload()
    {
        return view('versionmgr::package.upload');
    }

    public function list(Request $request)
    {
        return response()->json(
            $this->packageService->getPackageList($request->all())
        );
    }

    public function doUpload(Request $request)
    {
        $request->validate([
            'package' => 'required|file|mimes:zip|max:102400',
        ]);

        return response()->json(
            $this->packageService->uploadPackage($request->file('package'))
        );
    }

    public function delete(int $id)
    {
        return response()->json($this->packageService->deletePackage($id));
    }

    public function upgrade(int $id)
    {
        return response()->json($this->upgradeService->upgradeByPackage($id));
    }
}
