<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Http\Responses\ApiResponse;
use App\Models\ConfigGroup;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class ConfigGroupController extends Controller
{
    public function index(): JsonResponse
    {
        try {
            $groups = ConfigGroup::with(['items' => function ($query) {
                $query->where('status', 1)->orderBy('sort', 'asc');
            }])
                ->whereNull('app_id')
                ->orderBy('sort', 'asc')
                ->orderBy('id', 'asc')
                ->get();

            return response()->json(ApiResponse::success($groups));
        } catch (\Exception $e) {
            return response()->json(ApiResponse::error(50001, '获取配置分组失败：'.$e->getMessage()));
        }
    }

    public function store(Request $request): JsonResponse
    {
        try {
            $request->validate([
                'name' => 'required|string|max:50',
                'code' => 'required|string|max:50|unique:config_groups,code',
                'sort' => 'nullable|integer',
            ]);

            $group = ConfigGroup::create([
                'name' => $request->input('name'),
                'code' => $request->input('code'),
                'sort' => $request->input('sort', 0),
                'status' => 1,
            ]);

            return response()->json(ApiResponse::success($group, '创建分组成功'));
        } catch (\Exception $e) {
            return response()->json(ApiResponse::error(50001, '创建分组失败：'.$e->getMessage()));
        }
    }

    public function update(Request $request, int $id): JsonResponse
    {
        try {
            $group = ConfigGroup::find($id);

            if (! $group) {
                return response()->json(ApiResponse::error(40302, '分组不存在'));
            }

            $isSystem = in_array($group->code, self::SYSTEM_CONFIG_CODES);

            $rules = [
                'name' => 'required|string|max:50',
                'sort' => 'nullable|integer',
            ];
            if (!$isSystem) {
                $rules['code'] = 'required|string|max:50|unique:config_groups,code,'.$id;
            }
            $request->validate($rules);

            $updateData = [
                'name' => $request->input('name'),
                'sort' => $request->input('sort', $group->sort),
            ];
            if (!$isSystem) {
                $updateData['code'] = $request->input('code');
            }

            $group->update($updateData);

            return response()->json(ApiResponse::success($group, '更新分组成功'));
        } catch (\Exception $e) {
            return response()->json(ApiResponse::error(50001, '更新分组失败：'.$e->getMessage()));
        }
    }

    protected const SYSTEM_CONFIG_CODES = ['basic', 'upload', 'security', 'email'];

    public function destroy(int $id): JsonResponse
    {
        try {
            $group = ConfigGroup::find($id);

            if (! $group) {
                return response()->json(ApiResponse::error(40302, '分组不存在'));
            }

            if (in_array($group->code, self::SYSTEM_CONFIG_CODES)) {
                return response()->json(ApiResponse::error(40303, '系统内置配置分组不允许删除'));
            }

            DB::beginTransaction();
            $group->items()->delete();
            $group->delete();
            DB::commit();

            return response()->json(ApiResponse::success(null, '删除分组成功'));
        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json(ApiResponse::error(50001, '删除分组失败：'.$e->getMessage()));
        }
    }
}
