<?php

namespace App\Http\Controllers\Api\V1;

use App\Exceptions\DomainException;
use App\Http\Controllers\Controller;
use App\Http\Requests\DeviceStoreRequest;
use App\Models\DeviceToken;
use App\Support\ApiResponse;
use Illuminate\Http\Request;

class DeviceController extends Controller
{
    use ApiResponse;

    public function store(DeviceStoreRequest $request)
    {
        $user = $request->user();
        $data = $request->validated();

        $device = DeviceToken::query()->updateOrCreate(
            [
                'user_id' => $user->id,
                'device_id' => $data['device_id'],
                'provider' => $data['provider'],
            ],
            [
                'organization_id' => $user->organization_id,
                'device_name' => $data['device_name'] ?? null,
                'platform' => $data['platform'],
                'token' => $data['token'],
                'is_active' => true,
                'last_used_at' => now(),
            ]
        );

        return $this->success([
            'id' => $device->id,
            'device_id' => $device->device_id,
            'device_name' => $device->device_name,
            'platform' => $device->platform,
            'provider' => $device->provider,
            'is_active' => $device->is_active,
        ], 'Device registered.');
    }

    public function destroy(Request $request, DeviceToken $device)
    {
        if ((int) $device->user_id !== (int) $request->user()->id) {
            throw new DomainException('FORBIDDEN', 'You cannot remove this device token.', 403);
        }

        $device->delete();

        return $this->success(null, 'Device removed.');
    }
}
