<?php

namespace App\Http\Controllers\Api\V1\Guard;

use App\Http\Controllers\Controller;
use App\Services\MemberQrAccessService;
use App\Traits\ApiResponseTrait;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class MemberScanController extends Controller
{
    use ApiResponseTrait;

    public function __construct(
        protected MemberQrAccessService $memberQrAccessService
    ) {}

    /**
     * POST /api/v1/guard/member-scan
     * Security guard scans a member's QR code.
     */
    public function scan(Request $request): JsonResponse
    {
        $data = $request->validate([
            'qr_payload' => ['required', 'string'],
        ]);

        $result = $this->memberQrAccessService->validateScan(
            $data['qr_payload'],
            $request->user(),
        );

        $result['valid'] = (bool) ($result['granted'] ?? false);

        $code = $result['valid'] ? 200 : 422;

        return $this->ApiResponse($result, $result['message'], $code);
    }

    public function history(Request $request): JsonResponse
    {
        $request->validate([
            'member_id' => ['nullable', 'integer', 'exists:members,id'],
            'per_page'  => ['nullable', 'integer', 'min:1', 'max:200'],
        ]);

        $logs = $this->memberQrAccessService->getGuardHistory(
            $request->integer('member_id') ?: null,
            $request->integer('per_page', 50)
        );

        return $this->ApiResponse([
            'logs' => $logs->items(),
            'meta' => [
                'current_page' => $logs->currentPage(),
                'last_page'    => $logs->lastPage(),
                'per_page'     => $logs->perPage(),
                'total'        => $logs->total(),
            ],
        ], __('Success'), 200);
    }
}
