<?php

declare(strict_types=1);

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Support\ApiResponse;
use hg\apidoc\annotation as Apidoc;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;

#[Apidoc\Group('安装')]
#[Apidoc\Title('安装向导')]
final class InstallController extends Controller
{
    #[Apidoc\Title('安装状态')]
    #[Apidoc\Url('/api/install/status')]
    #[Apidoc\Method('GET')]
    public function status(): JsonResponse
    {
        return ApiResponse::success([
            'installed' => Storage::exists('installed.lock'),
            'database' => config('database.default'),
        ]);
    }

    #[Apidoc\Title('测试数据库连接')]
    #[Apidoc\Url('/api/install/database-test')]
    #[Apidoc\Method('POST')]
    public function databaseTest(Request $request): JsonResponse
    {
        $data = $request->validate([
            'host' => ['required', 'string'],
            'port' => ['required', 'integer'],
            'database' => ['required', 'string'],
            'username' => ['required', 'string'],
            'password' => ['nullable', 'string'],
        ]);

        config()->set('database.connections.install_test', [
            'driver' => 'mysql',
            'host' => $data['host'],
            'port' => $data['port'],
            'database' => $data['database'],
            'username' => $data['username'],
            'password' => $data['password'] ?? '',
            'charset' => 'utf8mb4',
            'collation' => 'utf8mb4_unicode_ci',
        ]);

        DB::connection('install_test')->select('select 1');

        return ApiResponse::success(['ok' => true], '数据库连接成功');
    }

    #[Apidoc\Title('执行安装')]
    #[Apidoc\Url('/api/install/run')]
    #[Apidoc\Method('POST')]
    public function run(Request $request): JsonResponse
    {
        $data = $request->validate([
            'admin_email' => ['required', 'email'],
            'admin_password' => ['required', 'string', 'min:6'],
            'fresh' => ['boolean'],
        ]);

        Artisan::call('quickquiz:install', [
            '--admin-email' => $data['admin_email'],
            '--admin-password' => $data['admin_password'],
            '--fresh' => (bool) ($data['fresh'] ?? false),
        ]);

        return ApiResponse::success([
            'output' => Artisan::output(),
            'installed' => true,
        ], '安装完成');
    }
}
