<?php

namespace App\Http\Controllers\Api\System\VersionManagement;

use App\Http\Controllers\Controller;
use App\Http\Requests\Api\System\VersionManagement\CheckForUpdateRequest;
use App\Models\System\VersionManagement\AppVersion;
use Illuminate\Http\JsonResponse;

class AppVersionController extends Controller
{
    /**
     * Check for app updates
     */
    public function checkForUpdate(CheckForUpdateRequest $request): JsonResponse
    {
        $app_version = AppVersion::latest()->where('os', $request->os)->first();

        if (! $app_version || $request->version === $app_version->version) {
            return $this->latestVersion();
        }

        if ($request->version < $app_version->version && $app_version->important) {
            return $this->requiredToUpdate();
        }

        if ((int) $request->version < (int) $app_version->version) {
            return $this->optionalToUpdate();
        }

        return $this->versionNotFound();
    }

    /**
     * Latest version
     */
    public function latestVersion(): JsonResponse
    {
        return response()->json(['update' => 'latest']);
    }

    /**
     * Required to update
     */
    public function requiredToUpdate(): JsonResponse
    {
        return response()->json(['update' => 'required']);
    }

    /**
     * Update not required, but should be
     */
    public function optionalToUpdate(): JsonResponse
    {
        return response()->json(['update' => 'optional']);
    }

    /**
     * App version not found
     */
    public function versionNotFound(): JsonResponse
    {
        return response()->json(['update' => 'version-not-found']);
    }
}
