<?php

namespace App\Http\Controllers;

use App\Services\Client\AccountService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Artisan;

class ScribeController extends Controller
{
    protected AccountService $accountService;

    public function __construct(AccountService $accountService)
    {
        $this->accountService = $accountService;
    }

    /**
     * 更新API文档的认证Token
     * 
     * 通过手机号获取验证码并登录，然后更新API文档的认证Token
     * 
     * @urlParam mobile string required 手机号码. Example: 13800138000
     * @response {
     *   "code": 200,
     *   "message": "Token更新成功",
     *   "data": {
     *     "token": "your_new_token_here"
     *   }
     * }
     */
    public function updateAuthToken(Request $request, $mobile)
    {
        try {
            // 1. 发送验证码
            $result = $this->accountService->sendVerifyCode($mobile);
            $code = $result['code'];

            // 2. 登录获取token
            $loginResult = $this->accountService->login($mobile, $code);
            $token = $loginResult['token'];

            // 3. 更新.env文件
            $envPath = base_path('.env');
            $envContent = File::get($envPath);
            
            // 更新或添加YOUR_AUTH_KEY
            if (preg_match('/^YOUR_AUTH_KEY=.*$/m', $envContent)) {
                $envContent = preg_replace('/^YOUR_AUTH_KEY=.*$/m', 'YOUR_AUTH_KEY=' . $token, $envContent);
            } else {
                $envContent .= "\nYOUR_AUTH_KEY=" . $token;
            }
            
            File::put($envPath, $envContent);


            // 5. 直接更新 auth.md 文件
            $authPath = base_path('.scribe/auth.md');
            if (File::exists($authPath)) {
                $authContent = File::get($authPath);
                $authContent = preg_replace(
                    '/\*\*`"Bearer [^"`]*"`\*\*/',
                    '**`"Bearer ' . $token . '"`**',
                    $authContent
                );
                File::put($authPath, $authContent);
            }

            // 6. 更新静态 HTML 文件
            $docsPath = public_path('docs/index.html');
            if (File::exists($docsPath)) {
                $docsContent = File::get($docsPath);
                $docsContent = preg_replace(
                    '/Bearer [a-zA-Z0-9|]*/',
                    'Bearer ' . $token,
                    $docsContent
                );
                File::put($docsPath, $docsContent);
            }

            return response()->json([
                'code' => 200,
                'message' => 'Token更新成功',
                'data' => [
                    'token' => $token
                ]
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'code' => 500,
                'message' => '更新失败: ' . $e->getMessage()
            ], 500);
        }
    }
}
