<?php

namespace App\Apps\Versionmgr\Controllers;

use App\Apps\Versionmgr\Services\RepairService;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;

class RepairController extends Controller
{
    protected RepairService $repairService;

    public function __construct(RepairService $repairService)
    {
        $this->repairService = $repairService;
    }

    /**
     * 修复页面
     */
    public function index()
    {
        $current = \App\Apps\Versionmgr\Models\SystemVersion::getCurrentVersion();

        return view('versionmgr::repair.index', [
            'currentVersion' => $current ? $current->version : '',
            'currentBuild' => $current ? $current->build : '',
        ]);
    }

    /**
     * 检查远程最新版本
     */
    public function check()
    {
        return response()->json($this->repairService->checkLatest());
    }

    /**
     * 下载完整程序包并解压、对比
     */
    public function prepare(Request $request)
    {
        $request->validate([
            'to_version' => 'required|string',
        ]);

        return response()->json(
            $this->repairService->prepare($request->input('to_version'))
        );
    }

    /**
     * 执行修复
     */
    public function execute(Request $request)
    {
        $request->validate([
            'files' => 'required|array|min:1',
            'files.*' => 'required|string',
        ]);

        return response()->json(
            $this->repairService->execute($request->input('files'))
        );
    }

    /**
     * 查询修复状态
     */
    public function status()
    {
        return response()->json($this->repairService->getStatus());
    }

    /**
     * 手动清理临时文件
     */
    public function cleanup()
    {
        return response()->json($this->repairService->cleanup());
    }
}
