<?php
namespace app\controller;

use think\Request;

class InstallController
{
    private function lockFile(): string
    {
        return root_path() . 'install.lock';
    }

    public function index()
    {
        if (is_file($this->lockFile())) {
            return '系统已安装，无需重复安装。';
        }
        // 直接渲染 public/install/index.html（不依赖模板目录配置）
        return view(app()->getRootPath() . 'public/install/index.html');
    }

    public function status()
    {
        return json(['installed' => is_file($this->lockFile())]);
    }

    public function run(Request $request)
    {
        if (is_file($this->lockFile())) {
            return json(['code' => 0, 'msg' => '系统已安装，禁止重复执行']);
        }

        $data = $request->post();
        $step = $data['step'] ?? 1; // Allow string steps like 'test_db'

        try {
            $svc = new \app\service\InstallService();

            if ($step === 'test_db') {
                $svc->testDbConnection($data);
                return json(['code' => 1, 'msg' => '数据库连接成功']);
            }

            // Convert numeric steps for backward compatibility if needed, though frontend sends numbers
            $stepNum = intval($step);

            if ($stepNum === 1) {
                $env = $svc->checkEnv();
                return json([
                    'code' => 1,
                    'msg'  => $env['pass'] ? '环境检查通过' : '环境存在风险，请查看详情',
                    'data' => $env,
                ]);
            }
            if ($stepNum === 2) {
                $svc->generateEnv($data);
                return json(['code' => 1, 'msg' => '.env 生成成功']);
            }
            if ($stepNum === 3) {
                $res = $svc->initDatabase($data);
                return json(['code' => 1, 'msg' => '数据库初始化完成', 'data' => $res]);
            }
            if ($stepNum === 4) {
                if (@file_put_contents($this->lockFile(), date('Y-m-d H:i:s')) === false) {
                    throw new \Exception('install.lock 写入失败，请检查项目根目录写权限');
                }
                return json(['code' => 1, 'msg' => '安装完成']);
            }

            return json(['code' => 0, 'msg' => '非法 step 参数']);
        } catch (\Throwable $e) {
            // For test_db, return the message directly
            if ($step === 'test_db') {
                return json(['code' => 0, 'msg' => $e->getMessage()]);
            }
            return json(['code' => 0, 'msg' => 'Step' . $step . '失败：' . $e->getMessage()]);
        }
    }
}
