<?php

namespace App\Http\Controllers\Admin\Room;

use App\Http\Controllers\Controller;
use App\Models\Room\RoomType;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class RoomTypeController extends Controller
{
    public function index(Request $request): JsonResponse
    {
        $query = RoomType::query()->withCount('rooms');
        $query->when($request->name, fn($q, $v) => $q->where('name', 'like', "%{$v}%"));
        $query->when($request->has('status'), fn($q) => $q->where('status', $request->status));

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

    public function store(Request $request): JsonResponse
    {
        $validated = $request->validate([
            'name' => 'required|string|max:50',
            'price' => 'nullable|numeric|min:0',
            'description' => 'nullable|string',
            'images' => 'nullable|array',
            'facilities' => 'nullable|array',
            'sort' => 'sometimes|integer',
            'status' => 'sometimes|integer|in:0,1',
        ]);
        return $this->success(RoomType::create($validated));
    }

    public function show(RoomType $roomType): JsonResponse
    {
        return $this->success($roomType->load('rooms'));
    }

    public function update(Request $request, RoomType $roomType): JsonResponse
    {
        $validated = $request->validate([
            'name' => 'sometimes|string|max:50',
            'price' => 'nullable|numeric|min:0',
            'description' => 'nullable|string',
            'images' => 'nullable|array',
            'facilities' => 'nullable|array',
            'sort' => 'sometimes|integer',
            'status' => 'sometimes|integer|in:0,1',
        ]);
        $roomType->update($validated);
        return $this->success($roomType);
    }

    public function destroy(RoomType $roomType): JsonResponse
    {
        if ($roomType->rooms()->exists()) {
            return $this->error('该房型下有房间，无法删除', 40001);
        }
        $roomType->delete();
        return $this->success(null);
    }
}
