<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Http\Responses\ApiResponse;
use App\Models\AttachmentGroup;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class AttachmentGroupController extends Controller
{
    public function index(): JsonResponse
    {
        try {
            $groups = AttachmentGroup::withCount('attachments')
                ->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',
                'description' => 'nullable|string|max:255',
                'sort' => 'nullable|integer',
            ]);

            $group = AttachmentGroup::create([
                'name' => $request->input('name'),
                'code' => 'group_'.uniqid(),
                'description' => $request->input('description'),
                '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 = AttachmentGroup::find($id);

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

            $request->validate([
                'name' => 'required|string|max:50',
                'description' => 'nullable|string|max:255',
                'sort' => 'nullable|integer',
            ]);

            $group->update([
                'name' => $request->input('name'),
                'description' => $request->input('description'),
                'sort' => $request->input('sort', $group->sort),
            ]);

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

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

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

            $group->attachments()->update(['group_id' => null]);
            $group->delete();

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