<?php

namespace App\Services;

use App\Models\AppVersion;
use Illuminate\Support\Facades\Storage;
use Symfony\Component\HttpFoundation\StreamedResponse;

class AppVersionService
{
    /**
     * 최신 버전 확인
     */
    public static function getLatestVersion(string $platform, int $currentVersionCode): array
    {
        $latest = AppVersion::where('platform', $platform)
            ->where('is_active', true)
            ->whereNotNull('published_at')
            ->orderByDesc('version_code')
            ->first();

        if (! $latest || $latest->version_code <= $currentVersionCode) {
            return [
                'has_update' => false,
                'latest_version' => null,
            ];
        }

        return [
            'has_update' => true,
            'latest_version' => [
                'id' => $latest->id,
                'version_code' => $latest->version_code,
                'version_name' => $latest->version_name,
                'release_notes' => $latest->release_notes,
                'force_update' => $latest->force_update,
                'apk_size' => $latest->apk_size,
                'download_url' => url("/api/v1/app/download/{$latest->id}"),
                'published_at' => $latest->published_at?->format('Y-m-d'),
            ],
        ];
    }

    /**
     * APK 다운로드
     */
    public static function downloadApk(int $id): StreamedResponse
    {
        $version = AppVersion::where('is_active', true)->findOrFail($id);

        if (! $version->apk_path || ! Storage::disk('app_releases')->exists($version->apk_path)) {
            abort(404, 'APK 파일을 찾을 수 없습니다.');
        }

        // 다운로드 수 증가
        $version->increment('download_count');

        $fileName = $version->apk_original_name ?: "app-v{$version->version_name}.apk";

        return Storage::disk('app_releases')->download($version->apk_path, $fileName);
    }
}
