<?php

declare(strict_types=1);

namespace Kylin\SensitiveWord\Http\Controllers;

use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use Kylin\SensitiveWord\Models\SensitiveWord;
use Kylin\SensitiveWord\Models\WordCategory;
use Kylin\SensitiveWord\Services\SensitiveWordService;

/**
 * 敏感词管理控制器
 *
 * 提供敏感词 CRUD、批量导入、增量同步、分类管理、检测过滤等 API
 */
class SensitiveWordController extends Controller
{
    public function __construct(
        private readonly SensitiveWordService $service
    ) {}

    /**
     * 敏感词列表
     */
    public function index(Request $request): JsonResponse
    {
        $query = SensitiveWord::query();

        if ($request->filled('category')) {
            $query->where('category', $request->input('category'));
        }

        if ($request->filled('risk_level')) {
            $query->where('risk_level', $request->input('risk_level'));
        }

        if ($request->filled('status')) {
            $query->where('status', $request->boolean('status'));
        }

        if ($request->filled('keyword')) {
            $query->where('word', 'like', '%' . $request->input('keyword') . '%');
        }

        $perPage = min($request->integer('per_page', 20), 100);

        return response()->json(
            $query->orderByDesc('id')->paginate($perPage)
        );
    }

    /**
     * 添加敏感词
     */
    public function store(Request $request): JsonResponse
    {
        $validated = $request->validate([
            'word'        => 'required|string|max:64',
            'category'    => 'required|string|max:32',
            'risk_level'  => 'nullable|in:high,medium,low',
            'source'      => 'nullable|string|max:50',
        ]);

        $word = $this->service->addWord(
            $validated['word'],
            $validated['category'],
            $validated['risk_level'] ?? 'medium',
            $validated['source'] ?? 'manual'
        );

        return response()->json([
            'message' => '敏感词添加成功',
            'data'    => $word,
        ], 201);
    }

    /**
     * 更新敏感词
     */
    public function update(Request $request, int $id): JsonResponse
    {
        $word = SensitiveWord::findOrFail($id);

        $validated = $request->validate([
            'word'        => 'sometimes|string|max:64',
            'category'    => 'sometimes|string|max:32',
            'risk_level'  => 'sometimes|in:high,medium,low',
            'status'      => 'sometimes|boolean',
        ]);

        $word->update($validated);
        $this->service->clearCache();

        return response()->json([
            'message' => '敏感词更新成功',
            'data'    => $word->fresh(),
        ]);
    }

    /**
     * 删除敏感词
     */
    public function destroy(int $id): JsonResponse
    {
        $word = SensitiveWord::findOrFail($id);
        $word->delete();
        $this->service->clearCache();

        return response()->json(['message' => '敏感词删除成功']);
    }

    /**
     * 批量导入
     */
    public function import(Request $request): JsonResponse
    {
        $validated = $request->validate([
            'words'              => 'required|array|max:10000',
            'words.*.word'       => 'required|string|max:64',
            'words.*.category'   => 'required|string|max:32',
            'words.*.risk_level' => 'nullable|in:high,medium,low',
        ]);

        $result = $this->service->batchImport($validated['words']);

        return response()->json([
            'message' => "批量导入完成：新增 {$result['imported']} 条，跳过 {$result['skipped']} 条",
            'data'    => $result,
        ]);
    }

    /**
     * 增量同步
     */
    public function sync(Request $request): JsonResponse
    {
        $sinceVersion = $request->input('since', '0.0.0');

        try {
            $result = $this->service->sync($sinceVersion);
            return response()->json([
                'message' => '同步成功',
                'data'    => $result,
            ]);
        } catch (\Throwable $e) {
            return response()->json([
                'message' => '同步失败: ' . $e->getMessage(),
            ], 500);
        }
    }

    /**
     * 分类列表
     */
    public function categories(): JsonResponse
    {
        return response()->json([
            'data' => $this->service->getCategories(),
        ]);
    }

    /**
     * 检测文本
     */
    public function detect(Request $request): JsonResponse
    {
        $validated = $request->validate([
            'text' => 'required|string|max:10000',
        ]);

        $hits = $this->service->detect($validated['text']);

        return response()->json([
            'contains' => !empty($hits),
            'hits'     => $hits,
        ]);
    }

    /**
     * 过滤文本
     */
    public function filterText(Request $request): JsonResponse
    {
        $validated = $request->validate([
            'text' => 'required|string|max:10000',
            'mode' => 'nullable|in:replace,block,warn',
        ]);

        try {
            $filtered = $this->service->filter($validated['text'], $validated['mode'] ?? null);
            return response()->json([
                'original' => $validated['text'],
                'filtered' => $filtered,
            ]);
        } catch (\RuntimeException $e) {
            return response()->json([
                'message' => $e->getMessage(),
            ], 422);
        }
    }

    /**
     * 词库统计
     */
    public function statistics(): JsonResponse
    {
        return response()->json([
            'data' => $this->service->getStatistics(),
        ]);
    }

    /**
     * 初始化默认分类
     */
    public function initCategories(): JsonResponse
    {
        $this->service->initDefaultCategories();

        return response()->json([
            'message' => '默认分类初始化完成',
        ]);
    }
}
