<?php

namespace App\Http\Controllers\Api\V1;

use App\Http\Controllers\Controller;
use App\Http\Requests\Api\V1\QrCode\AttachScanNoteRequest;
use App\Http\Requests\Api\V1\QrCode\GenerateQrRequest;
use App\Http\Requests\Api\V1\QrCode\ScanQrRequest;
use App\Http\Resources\Api\QrCodeResource;
use App\Repositories\MemberAccessLogRepository;
use App\Services\QrCodeService;
use App\Traits\ApiResponseTrait;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class QrCodeController extends Controller
{
    use ApiResponseTrait;

    public function __construct(
        protected QrCodeService $qrCodeService,
        protected MemberAccessLogRepository $memberAccessLogRepository
    ) {}


    public function generate(GenerateQrRequest $request)
    {
        $qrCode = $this->qrCodeService->generate($request->user() , $request->validated());

        return $this->ApiResponse(
            new QrCodeResource($qrCode),
            __('dashboard.qr_code_generated'),
            201
        );
    }


    public function scan(ScanQrRequest $request): JsonResponse
    {
        $result = $this->qrCodeService->scan(
            $request->validated('code'),
            $request->user()
        );

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

        // Same localization as other API endpoints (e.g. GameController): one string via __() for the active locale.
        $message = $result['message'] ?? __('Success');

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

    
    public function attachScanNote(AttachScanNoteRequest $request)
    {
        $validated = $request->validated();
        $updateNote = $request->exists('note');

        $log = $this->memberAccessLogRepository->attachNoteForScanner(
            (int) $validated['scan_id'],
            (int) $request->user()->id,
            $updateNote ? ($validated['note'] ?? null) : null,
            $updateNote
        );

        if ($log === null) {
            return $this->ApiResponse([], __('dashboard.qr_scan_event_not_found'), 404);
        }

        return $this->ApiResponse([
            'scan_id' => $log->id,
            'note'    => $log->note,
        ], __('dashboard.qr_scan_note_saved'), 200);
    }

    public function myQrCodes(Request $request)
    {
        $qrCodes = $request->user()
            ->qrCodes()
            ->latest()
            ->paginate(20);

        return $this->ApiResponse(
            QrCodeResource::collection($qrCodes),
            'Success',
            200
        );
    }
}
