<?php

namespace App\Http\Controllers\Api\V1;

use App\Http\Resources\Api\V1\DeviceResource;
use App\Models\Device;
use App\Services\WorkspaceEngine;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

/**
 * Devices — read the workspace's connected WhatsApp numbers.
 *
 * Reuses the same Device::forCurrentWorkspace() scope the mobile-app
 * DeviceController and the web DevicesController query. Each row is stamped
 * with the workspace's messaging engine (the devices table has no per-row
 * provider column) before being wrapped in the public { data } envelope.
 */
class DeviceController extends V1Controller
{
    /** GET /api/v1/devices — list the workspace's WhatsApp devices. */
    public function index(Request $request): JsonResponse
    {
        $engine = $this->engine();

        $items = Device::query()
            ->forCurrentWorkspace()
            ->orderByDesc('active')
            ->orderByDesc('id')
            ->get()
            ->map(function (Device $d) use ($engine) {
                $d->engine = $engine;
                return (new DeviceResource($d))->resolve();
            })
            ->values();

        return $this->ok($items, ['count' => $items->count()]);
    }

    /** GET /api/v1/devices/{id} — one device. */
    public function show(int $id): JsonResponse
    {
        $device = Device::query()->forCurrentWorkspace()->find($id);
        if (!$device) {
            return $this->fail('not_found', 'Device not found.', 404);
        }

        $device->engine = $this->engine();

        return $this->ok((new DeviceResource($device))->resolve());
    }

    /** Current workspace's messaging engine (unofficial / waba / twilio …). */
    private function engine(): ?string
    {
        try {
            return WorkspaceEngine::for($this->workspaceId());
        } catch (\Throwable $e) {
            return null;
        }
    }
}
