<?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\FilterMode;
use Kylin\WordFilter\Enums\WordFilterErrorCode;
use Kylin\WordFilter\Exceptions\WordFilterException;
use Kylin\WordFilter\Services\WordFilterService;

class WordFilterController extends BaseController
{
    public function __construct(
        private readonly WordFilterService $filterService,
    ) {}

    /**
     * 文本过滤
     */
    public function filter(Request $request): JsonResponse
    {
        $request->validate([
            'text' => 'required|string|max:10000',
            'scope' => 'nullable|array',
            'scope.categories' => 'nullable|array',
            'scope.severities' => 'nullable|array',
            'scope.min_severity' => 'nullable|string|in:low,moderate,high,severe',
        ]);

        $result = $this->filterService->filter(
            $request->input('text'),
            $request->input('scope'),
        );

        // 拦截模式下，包含敏感词则返回错误
        $mode = FilterMode::from($result['mode']);
        if ($mode === FilterMode::Block && $result['has_sensitive']) {
            throw WordFilterException::fromCode(
                WordFilterErrorCode::SensitiveWordBlocked,
                [
                    'matches' => $result['matches'],
                    'risk_level' => $result['risk_level'],
                ],
            );
        }

        return ApiResponse::success($result);
    }

    /**
     * 批量过滤
     */
    public function batchFilter(Request $request): JsonResponse
    {
        $maxSize = config('kylin-word-filter.batch_max_size', 100);

        $request->validate([
            'texts' => 'required|array|max:' . $maxSize,
            'texts.*' => 'required|string|max:10000',
            'scope' => 'nullable|array',
            'scope.categories' => 'nullable|array',
            'scope.severities' => 'nullable|array',
            'scope.min_severity' => 'nullable|string|in:low,moderate,high,severe',
        ]);

        $results = $this->filterService->batchFilter(
            $request->input('texts'),
            $request->input('scope'),
        );

        return ApiResponse::success($results);
    }

    /**
     * 获取分类列表
     */
    public function categories(): JsonResponse
    {
        $categories = config('kylin-word-filter.categories', []);

        $list = [];

        foreach ($categories as $riskLevel => $items) {
            foreach ($items as $code => $name) {
                $list[] = [
                    'code' => $code,
                    'name' => $name,
                    'risk_level' => $riskLevel,
                ];
            }
        }

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