<?php

declare(strict_types=1);

namespace App\Http\Controllers;

use App\Models\UserDevice;
use App\Support\ApiResponse;
use Illuminate\Http\Request;

class DeviceController extends Controller
{
    public function index(Request $request)
    {
        $devices = UserDevice::query()
            ->where('user_id', $request->user()->id)
            ->latest('last_used_at')
            ->latest('id')
            ->get()
            ->map(fn (UserDevice $device) => $this->transform($device));

        return ApiResponse::success(['items' => $devices]);
    }

    public function destroy(Request $request, UserDevice $device)
    {
        $this->ensureOwner($request, $device);
        $device->delete();

        return ApiResponse::success(message: 'دستگاه حذف شد.');
    }

    public function block(Request $request, UserDevice $device)
    {
        $this->ensureOwner($request, $device);
        $device->update(['is_blocked' => true]);

        return ApiResponse::success($this->transform($device->fresh()), 'دستگاه مسدود شد.');
    }

    public function unblock(Request $request, UserDevice $device)
    {
        $this->ensureOwner($request, $device);
        $device->update(['is_blocked' => false]);

        return ApiResponse::success($this->transform($device->fresh()), 'مسدودیت دستگاه برداشته شد.');
    }

    private function ensureOwner(Request $request, UserDevice $device): void
    {
        if ((int) $device->user_id !== (int) $request->user()->id && ! $request->user()->hasRole('admin')) {
            abort(403, 'دسترسی به این دستگاه مجاز نیست.');
        }
    }

    private function transform(UserDevice $device): array
    {
        return [
            'id' => $device->id,
            'name' => $device->name,
            'device_type' => $device->device_type,
            'platform' => $device->platform,
            'browser' => $device->browser,
            'ip' => $device->ip,
            'is_current' => (bool) $device->is_current,
            'is_blocked' => (bool) $device->is_blocked,
            'last_used_at' => $device->last_used_at?->toISOString(),
            'created_at' => $device->created_at?->toISOString(),
        ];
    }
}
