<?php

namespace App\Http\Controllers\Admin\Finance;

use App\Http\Controllers\Controller;
use App\Models\Finance\FinanceCategory;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class FinanceCategoryController extends Controller
{
    public function index(Request $request): JsonResponse
    {
        $query = FinanceCategory::query();
        $query->when($request->type, fn($q, $v) => $q->where('type', $v));
        $query->when($request->has('status'), fn($q) => $q->where('status', $request->status));

        $categories = $query->orderBy('sort')->get();

        // 构建树形结构
        $tree = $categories->where('parent_id', 0)->values()->map(function ($item) use ($categories) {
            $item->children = $categories->where('parent_id', $item->id)->values();
            return $item;
        });

        return $this->success($tree);
    }

    public function store(Request $request): JsonResponse
    {
        $validated = $request->validate([
            'name' => 'required|string|max:50',
            'type' => 'required|integer|in:1,2',
            'parent_id' => 'sometimes|integer',
            'sort' => 'sometimes|integer',
            'status' => 'sometimes|integer|in:0,1',
        ]);

        if (!empty($validated['parent_id'])) {
            $parent = FinanceCategory::find($validated['parent_id']);
            $validated['level'] = $parent ? $parent->level + 1 : 1;
        }

        return $this->success(FinanceCategory::create($validated));
    }

    public function show(FinanceCategory $financeCategory): JsonResponse
    {
        return $this->success($financeCategory->load('children'));
    }

    public function update(Request $request, FinanceCategory $financeCategory): JsonResponse
    {
        $validated = $request->validate([
            'name' => 'sometimes|string|max:50',
            'type' => 'sometimes|integer|in:1,2',
            'parent_id' => 'sometimes|integer',
            'sort' => 'sometimes|integer',
            'status' => 'sometimes|integer|in:0,1',
        ]);

        $financeCategory->update($validated);

        return $this->success($financeCategory);
    }

    public function destroy(FinanceCategory $financeCategory): JsonResponse
    {
        if ($financeCategory->children()->count() > 0) {
            return $this->error('存在子分类，无法删除', 40001);
        }

        $financeCategory->delete();

        return $this->success(null);
    }
}
