<?php

namespace App\Services\Update;

use App\DTOs\ProductOwner\AdminUpdateCheckData;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Http;
use RuntimeException;

class PlatformUpdateService
{
    public function __construct(
        private readonly AdminUpdateService $adminUpdateService,
    ) {}

    public function stageUpdate(AdminUpdateCheckData $check): string
    {
        if (! $check->updateAvailable) {
            throw new RuntimeException('No admin update is available.');
        }

        if (! $this->adminUpdateService->tempPathConfigured()) {
            throw new RuntimeException('Configure a writable temporary update path before applying updates.');
        }

        if (empty($check->downloadUrl)) {
            throw new RuntimeException('No update package URL is configured on the Product Owner platform.');
        }

        $tempPath = $this->adminUpdateService->tempPath();
        $version = $check->latestVersion ?? 'latest';
        $filename = 'admin-update-'.$version.'.zip';
        $destination = rtrim($tempPath, DIRECTORY_SEPARATOR).DIRECTORY_SEPARATOR.$filename;

        $response = Http::timeout(120)->get($check->downloadUrl);

        if (! $response->successful()) {
            throw new RuntimeException('Failed to download the admin update package.');
        }

        File::put($destination, $response->body());

        return $destination;
    }
}
