<?php

namespace App\Http\Controllers;

use App\Models\AppVersion;
use App\Services\AppVersionService;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Illuminate\View\View;
use Symfony\Component\HttpFoundation\StreamedResponse;

class AppVersionController extends Controller
{
    public function __construct(
        private readonly AppVersionService $appVersionService
    ) {}

    /**
     * 버전 목록 + 등록 폼
     */
    public function index(Request $request): View
    {
        $isSuperAdmin = auth()->user()?->is_super_admin ?? false;
        $versions = $this->appVersionService->list(withTrashed: $isSuperAdmin);

        return view('app-versions.index', compact('versions', 'isSuperAdmin'));
    }

    /**
     * 새 버전 등록
     */
    public function store(Request $request): RedirectResponse
    {
        $request->validate([
            'version_code' => 'required|integer|min:1|unique:app_versions,version_code',
            'version_name' => 'required|string|max:20',
            'platform' => 'required|in:android,ios',
            'release_notes' => 'nullable|string',
            'force_update' => 'nullable|boolean',
            'apk_file' => 'nullable|file|max:204800', // 200MB
        ]);

        $this->appVersionService->store(
            $request->only(['version_code', 'version_name', 'platform', 'release_notes', 'force_update']),
            $request->file('apk_file')
        );

        return redirect()->route('app-versions.index')
            ->with('success', '새 버전이 등록되었습니다.');
    }

    /**
     * 버전 수정
     */
    public function update(Request $request, int $id): RedirectResponse
    {
        $request->validate([
            'version_code' => "required|integer|min:1|unique:app_versions,version_code,{$id}",
            'version_name' => 'required|string|max:20',
            'platform' => 'required|in:android,ios',
            'release_notes' => 'nullable|string',
            'force_update' => 'nullable|boolean',
            'apk_file' => 'nullable|file|max:204800',
        ]);

        $this->appVersionService->update(
            $id,
            $request->only(['version_code', 'version_name', 'platform', 'release_notes', 'force_update']),
            $request->file('apk_file')
        );

        return redirect()->route('app-versions.index')
            ->with('success', '버전이 수정되었습니다.');
    }

    /**
     * APK 다운로드
     */
    public function download(int $id): StreamedResponse
    {
        $version = AppVersion::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 ?: "sam-v{$version->version_name}.apk";

        return Storage::disk('app_releases')->download($version->apk_path, $fileName, [
            'Content-Type' => 'application/vnd.android.package-archive',
        ]);
    }

    /**
     * 활성 토글
     */
    public function toggleActive(int $id): RedirectResponse
    {
        $version = $this->appVersionService->toggleActive($id);
        $status = $version->is_active ? '활성화' : '비활성화';

        return redirect()->route('app-versions.index')
            ->with('success', "v{$version->version_name}이 {$status}되었습니다.");
    }

    /**
     * 삭제
     */
    public function destroy(int $id): RedirectResponse
    {
        $this->appVersionService->destroy($id);

        return redirect()->route('app-versions.index')
            ->with('success', '버전이 삭제되었습니다.');
    }

    /**
     * 복구 (슈퍼관리자 전용)
     */
    public function restore(int $id): RedirectResponse
    {
        $version = $this->appVersionService->restore($id);

        return redirect()->route('app-versions.index')
            ->with('success', "v{$version->version_name}이 복구되었습니다.");
    }

    /**
     * 영구 삭제 (슈퍼관리자 전용)
     */
    public function forceDestroy(int $id): RedirectResponse
    {
        $this->appVersionService->forceDestroy($id);

        return redirect()->route('app-versions.index')
            ->with('success', '버전이 영구 삭제되었습니다.');
    }
}
