<?php

namespace App\Modules\Devices\Controllers;

use App\Core\BaseApiController;
use App\Modules\Devices\Services\DeviceAuthService;
use CodeIgniter\HTTP\ResponseInterface;

/**
 * Device Authentication Controller
 * 
 * Handles device authentication endpoints.
 */
class DeviceAuthController extends BaseApiController
{
    protected DeviceAuthService $deviceAuthService;

    public function __construct()
    {
        $this->deviceAuthService = new DeviceAuthService();
    }

    /**
     * Device login endpoint
     * 
     * Authenticates device using device_code and api_key.
     * 
     * POST /api/device/login
     * Body: { "device_code": "", "api_key": "" }
     * 
     * @return ResponseInterface
     */
    public function login(): ResponseInterface
    {
        // Get JSON input
        $input = $this->request->getJSON(true);

        // Validate input
        if (empty($input['device_code']) || empty($input['api_key'])) {
            return $this->errorResponse(
                'device_code and api_key are required',
                null,
                null,
                400
            );
        }

        // Authenticate device
        $deviceData = $this->deviceAuthService->authenticate(
            $input['device_code'],
            $input['api_key']
        );

        if (!$deviceData) {
            return $this->errorResponse(
                'Invalid device credentials',
                null,
                null,
                401
            );
        }

        // Return success response
        return $this->successResponse(
            [
                'device_id'   => $deviceData['device_id'],
                'device_code' => $deviceData['device_code'],
            ],
            'Device authenticated'
        );
    }
}
