<?php

namespace Modules\RestApi\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use App\Models\DeliveryExecutive;
use Modules\RestApi\Entities\DeviceToken;
use Modules\RestApi\Traits\ApiResponse;

class DeviceController extends Controller
{
    use ApiResponse;

    public function register(Request $request)
    {
        $validated = $request->validate([
            'device_id' => 'required|string|max:255',
            'registration_id' => 'required|string',
            'type' => 'required|string|max:50',
            'details' => 'nullable',
            'delivery_executive_code' => 'required|string|max:255',
        ]);

        $deliveryExecutive = DeliveryExecutive::where('unique_code', $validated['delivery_executive_code'])->first();

        if (! $deliveryExecutive) {
            return $this->errorResponse('Invalid delivery executive code', 404);
        }

        $details = $validated['details'] ?? null;

        if (is_array($details)) {
            $details = json_encode($details);
        }

        $device = DeviceToken::updateOrCreate(
            [
                'device_id' => $validated['device_id'],
                'user_id' => $deliveryExecutive->id,
            ],
            [
                'registration_id' => $validated['registration_id'],
                'status' => 'active',
                'type' => $validated['type'],
                'details' => $details,
            ]
        );

        return $this->successResponse([
            'details' => $device->details,
            'device_id' => $device->device_id,
            'registration_id' => $device->registration_id,
            'status' => $device->status,
            'type' => $device->type,
            'user_id' => $device->user_id,
        ], 'Device registered successfully');
    }

    public function unregister(Request $request)
    {
        $validated = $request->validate([
            'device_id' => 'required|string|max:255',
            'delivery_executive_code' => 'required|string|max:255',
        ]);

        $deliveryExecutive = DeliveryExecutive::where('unique_code', $validated['delivery_executive_code'])->first();

        if (! $deliveryExecutive) {
            return $this->errorResponse('Invalid delivery executive code', 404);
        }

        $device = DeviceToken::where('device_id', $validated['device_id'])
            ->where('user_id', $deliveryExecutive->id)
            ->first();

        if (! $device) {
            return $this->notFoundResponse('Device not found');
        }

        $device->status = 'inactive';
        $device->save();

        return $this->successResponse([
            'details' => $device->details,
            'device_id' => $device->device_id,
            'registration_id' => $device->registration_id,
            'status' => $device->status,
            'type' => $device->type,
            'user_id' => $device->user_id,
        ], 'Device unregistered successfully');
    }

}

