<?php

namespace Kylin\WordFilter\Http\Controllers;

use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Kylin\Core\ApiResponse;
use Kylin\Core\Controllers\BaseController;
use Kylin\WordFilter\Enums\WordFilterErrorCode;
use Kylin\WordFilter\Exceptions\WordFilterException;
use Kylin\WordFilter\Services\WordSyncService;

class WordVersionController extends BaseController
{
    public function __construct(
        private readonly WordSyncService $syncService,
    ) {}

    /**
     * 获取词库版本
     */
    public function version(): JsonResponse
    {
        $version = $this->syncService->getVersion();

        return ApiResponse::success($version);
    }

    /**
     * 增量同步词库
     */
    public function sync(Request $request): JsonResponse
    {
        $request->validate([
            'from_version' => 'required|string',
        ]);

        $fromVersion = $request->input('from_version');

        // "0" 表示全量同步，其他值必须是语义化版本号
        if ($fromVersion !== '0' && ! preg_match('/^\d+\.\d+\.\d+$/', $fromVersion)) {
            throw WordFilterException::fromCode(WordFilterErrorCode::SyncVersionInvalid);
        }

        // "0" 转换为 "0.0.0" 统一处理
        if ($fromVersion === '0') {
            $fromVersion = '0.0.0';
        }

        $result = $this->syncService->syncFromVersion($fromVersion);

        return ApiResponse::success($result);
    }
}
