<?php

namespace App\Http\Controllers\Update;

use App\Http\Controllers\Controller;
use App\Http\Requests\Update\SaveUpdateSettingsRequest;
use App\Models\Setting;
use App\Contracts\CoreHashValidatorContract;
use App\Services\Update\AdminUpdateService;
use App\Services\Update\PlatformUpdateService;
use Illuminate\Http\RedirectResponse;
use Illuminate\View\View;
use RuntimeException;

class UpdateController extends Controller
{
    public function __construct(
        private readonly AdminUpdateService $adminUpdateService,
        private readonly PlatformUpdateService $platformUpdateService,
        private readonly CoreHashValidatorContract $coreHashValidator,
    ) {}

    public function index(): View
    {
        $this->authorize('viewAny', Setting::class);

        $check = $this->adminUpdateService->checkForUpdate();

        return view('updates.index', [
            'current' => $this->adminUpdateService->currentVersion(),
            'check' => $check,
            'lastCheckedAt' => $this->adminUpdateService->lastCheckedAt(),
            'tempPath' => $this->adminUpdateService->tempPath(),
            'tempPathConfigured' => $this->adminUpdateService->tempPathConfigured(),
            'canApplyUpdate' => $this->adminUpdateService->canApplyUpdate($check),
        ]);
    }

    public function check(): RedirectResponse
    {
        $this->authorize('update', Setting::class);

        $this->adminUpdateService->checkForUpdate(force: true);

        return redirect()
            ->route('updates.index')
            ->with('status', 'Update check completed.');
    }

    public function saveSettings(SaveUpdateSettingsRequest $request): RedirectResponse
    {
        $path = $request->string('update_temp_path')->toString();
        $this->adminUpdateService->saveTempPath($path);
        $this->adminUpdateService->ensureTempPath();

        return redirect()
            ->route('updates.index')
            ->with('status', 'Update settings saved.');
    }

    public function apply(): RedirectResponse
    {
        $this->authorize('update', Setting::class);

        $integrity = $this->coreHashValidator->validate();

        if ($integrity['status'] === 'tampered') {
            return back()->with('error', $integrity['message'] ?? 'Updates are disabled because core application files were modified.');
        }

        $check = $this->adminUpdateService->checkForUpdate(force: true);

        try {
            $packagePath = $this->platformUpdateService->stageUpdate($check);
        } catch (RuntimeException $exception) {
            return back()->with('error', $exception->getMessage());
        }

        return redirect()
            ->route('updates.index')
            ->with('status', 'Update package downloaded to '.$packagePath.'. Complete deployment using your release process.');
    }
}
