<?php

namespace App\Services;

use App\Models\AppVersion;
use Illuminate\Http\UploadedFile;
use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Support\Facades\Storage;

class AppVersionService
{
    /**
     * 버전 목록 (페이지네이션)
     */
    public function list(bool $withTrashed = false, int $perPage = 20): LengthAwarePaginator
    {
        $query = AppVersion::orderByDesc('version_code');

        if ($withTrashed) {
            $query->withTrashed();
        }

        return $query->paginate($perPage);
    }

    /**
     * 새 버전 등록
     */
    public function store(array $data, ?UploadedFile $apkFile = null): AppVersion
    {
        if ($apkFile) {
            $data['apk_original_name'] = $apkFile->getClientOriginalName();
            $data['apk_size'] = $apkFile->getSize();
            $data['apk_path'] = $apkFile->store('apk', 'app_releases');
        }

        $data['created_by'] = auth()->id();
        $data['published_at'] = $data['published_at'] ?? now();

        return AppVersion::create($data);
    }

    /**
     * 버전 수정
     */
    public function update(int $id, array $data, ?UploadedFile $apkFile = null): AppVersion
    {
        $version = AppVersion::findOrFail($id);

        if ($apkFile) {
            // 기존 APK 삭제
            if ($version->apk_path && Storage::disk('app_releases')->exists($version->apk_path)) {
                Storage::disk('app_releases')->delete($version->apk_path);
            }

            $data['apk_original_name'] = $apkFile->getClientOriginalName();
            $data['apk_size'] = $apkFile->getSize();
            $data['apk_path'] = $apkFile->store('apk', 'app_releases');
        }

        $data['updated_by'] = auth()->id();
        $version->update($data);

        return $version;
    }

    /**
     * 활성 토글
     */
    public function toggleActive(int $id): AppVersion
    {
        $version = AppVersion::findOrFail($id);
        $version->is_active = ! $version->is_active;
        $version->updated_by = auth()->id();
        $version->save();

        return $version;
    }

    /**
     * 삭제 (소프트)
     */
    public function destroy(int $id): void
    {
        $version = AppVersion::findOrFail($id);
        $version->delete();
    }

    /**
     * 복구
     */
    public function restore(int $id): AppVersion
    {
        $version = AppVersion::onlyTrashed()->findOrFail($id);
        $version->restore();

        return $version;
    }

    /**
     * 영구 삭제
     */
    public function forceDestroy(int $id): void
    {
        $version = AppVersion::onlyTrashed()->findOrFail($id);

        // APK 파일 삭제
        if ($version->apk_path && Storage::disk('app_releases')->exists($version->apk_path)) {
            Storage::disk('app_releases')->delete($version->apk_path);
        }

        $version->forceDelete();
    }
}
