<?php

namespace App\Http\Controllers\Admin\Kb;

use App\Http\Controllers\Controller;
use App\Models\Kb\KbArticle;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class KbArticleController extends Controller
{
    public function index(Request $request): JsonResponse
    {
        $query = KbArticle::query()->with(['category', 'author']);
        $query->when($request->category_id, fn($q, $v) => $q->where('category_id', $v));
        $query->when($request->filled('status'), fn($q) => $q->where('status', $request->status));
        $query->when($request->filled('visibility'), fn($q) => $q->where('visibility', $request->visibility));
        $query->when($request->keyword, fn($q, $v) => $q->where('title', 'like', "%{$v}%"));

        return $this->paginate($query->latest()->paginate($request->input('per_page', 15)));
    }

    public function store(Request $request): JsonResponse
    {
        $validated = $request->validate([
            'title' => 'required|string|max:255',
            'content' => 'nullable|string',
            'category_id' => 'nullable|exists:kb_categories,id',
            'visibility' => 'nullable|integer|in:1,2',
            'cover_image' => 'nullable|string|max:255',
            'attachments' => 'nullable|array',
        ]);
        $validated['author_id'] = auth()->id();
        $validated['status'] = 0;

        $article = KbArticle::create($validated);
        return $this->success($article->load(['category', 'author']));
    }

    public function show(KbArticle $kbArticle): JsonResponse
    {
        $kbArticle->increment('views');
        return $this->success($kbArticle->load(['category', 'author']));
    }

    public function update(Request $request, KbArticle $kbArticle): JsonResponse
    {
        $validated = $request->validate([
            'title' => 'sometimes|string|max:255',
            'content' => 'nullable|string',
            'category_id' => 'nullable|exists:kb_categories,id',
            'visibility' => 'nullable|integer|in:1,2',
            'cover_image' => 'nullable|string|max:255',
            'attachments' => 'nullable|array',
        ]);
        $kbArticle->update($validated);
        return $this->success($kbArticle);
    }

    public function destroy(KbArticle $kbArticle): JsonResponse
    {
        $kbArticle->delete();
        return $this->success(null);
    }

    public function publish(KbArticle $kbArticle): JsonResponse
    {
        if ($kbArticle->status >= 2) {
            return $this->error('当前状态不允许发布');
        }
        $kbArticle->update(['status' => 2, 'published_at' => now()]);
        return $this->success($kbArticle);
    }

    public function offline(KbArticle $kbArticle): JsonResponse
    {
        if ($kbArticle->status !== 2) {
            return $this->error('仅已发布文章可下架');
        }
        $kbArticle->update(['status' => 3]);
        return $this->success($kbArticle);
    }
}
