<?php

declare(strict_types=1);

namespace Kylin\Parking\Http\Controllers;

use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Kylin\Core\ApiResponse;
use Kylin\Core\Controllers\BaseController;
use Kylin\Parking\Services\ParkingService;

/**
 * 停车管理控制器
 *
 * 提供车辆入场、出场、月卡办理/续费等 HTTP 接口。
 *
 * 法律合规：
 *  - 所有写操作通过 ParkingService 执行，自动记录审计日志
 *  - 车牌号加密存储（依据《个人信息保护法》第四十二条）
 */
class ParkingController extends BaseController
{
    public function __construct(private readonly ParkingService $service) {}

    /**
     * 车辆入场
     */
    public function entry(Request $request): JsonResponse
    {
        $data = $request->validate([
            'lot_id' => 'required|integer',
            'plate_no' => 'required|string|max:20',
            'confidence' => 'nullable|numeric|min:0|max:1',
        ]);

        $record = $this->service->vehicleEntry($data);
        return ApiResponse::success($record, '入场成功');
    }

    /**
     * 车辆出场
     */
    public function exit(Request $request): JsonResponse
    {
        $data = $request->validate([
            'lot_id' => 'required|integer',
            'plate_no' => 'required|string|max:20',
        ]);

        $result = $this->service->vehicleExit((int) $data['lot_id'], (string) $data['plate_no']);
        return ApiResponse::success($result, $result['free'] ? '免费放行' : '计费完成');
    }

    /**
     * 办理月卡
     */
    public function createMonthlyCard(Request $request): JsonResponse
    {
        $data = $request->validate([
            'lot_id' => 'required|integer',
            'plate_no' => 'required|string|max:20',
            'owner_name' => 'required|string|max:50',
            'owner_phone' => 'nullable|string|max:20',
            'duration_months' => 'required|integer|min:1|max:36',
        ]);

        $card = $this->service->createMonthlyCard($data);
        return ApiResponse::success($card, '月卡办理成功');
    }

    /**
     * 月卡续费
     */
    public function renewMonthlyCard(Request $request, int $id): JsonResponse
    {
        $data = $request->validate(['duration_months' => 'required|integer|min:1|max:36']);

        $card = $this->service->renewMonthlyCard($id, (int) $data['duration_months']);
        return ApiResponse::success($card, '月卡续费成功');
    }

    /**
     * 即将到期月卡列表（用于提醒）
     */
    public function expiringSoon(): JsonResponse
    {
        return ApiResponse::success($this->service->getExpiringSoonCards());
    }
}
