<?php

namespace App\Http\Controllers\Api\BadgeScan;

use App\Http\Controllers\Api\Core\BaseApiController;
use App\Services\BadgeScan\BadgeScanService;
use App\Services\SchoolYears\SchoolYearContextService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Symfony\Component\HttpFoundation\Response;

class BadgeScanController extends BaseApiController
{
    public function __construct(
        private BadgeScanService $badgeScan,
        private SchoolYearContextService $schoolYears,
    ) {
        parent::__construct();
    }

    /**
     * Public kiosk endpoint — POST JSON or form (legacy RFIDController::process).
     */
    public function scan(Request $request): JsonResponse
    {
        $validator = Validator::make($request->all(), [
            'badge_scan' => ['required', 'string', 'max:255'],
            'school_year' => ['nullable', 'string', 'max:50'],
            'semester' => ['nullable', 'string', 'max:50'],
        ]);

        if ($validator->fails()) {
            return $this->respondValidationError($validator->errors()->toArray());
        }

        $payload = $validator->validated();
        $context = $this->schoolYears->options($payload['school_year'] ?? null, $payload['semester'] ?? null);
        $result = $this->badgeScan->processScan(
            $payload['badge_scan'],
            $context['school_year'] ?? null,
            $context['semester'] ?? null
        );

        if (! $result['recognized']) {
            return $this->error($result['message'], Response::HTTP_NOT_FOUND);
        }

        return $this->success([
            'recognized' => true,
            'user_id' => $result['user_id'] ?? null,
            'display_name' => $result['display_name'] ?? null,
        ], $result['message']);
    }

    /**
     * Authenticated scan log listing (legacy RFIDController::log).
     */
    public function logs(Request $request): JsonResponse
    {
        $context = $this->schoolYears->options(
            $request->query('school_year'),
            $request->query('semester')
        );

        return $this->success([
            'logs' => $this->badgeScan->scanLogRows(
                $context['school_year'] ?? null,
                $context['semester'] ?? null
            ),
            'meta' => $context,
        ]);
    }
}
