<?php

declare(strict_types=1);

namespace App\Http\Controllers\Api\V1;

use App\Http\Controllers\Controller;
use App\Http\Resources\ServiceResource;
use App\Models\Service;
use App\Services\Provisioning\VirtFusionService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\AnonymousResourceCollection;
use Illuminate\Support\Facades\Log;

class CustomerServiceController extends Controller
{
    public function index(Request $request): AnonymousResourceCollection
    {
        $services = $request->user()
            ->services()
            ->with('plan:id,name,price,billing_cycle')
            ->latest()
            ->paginate(15);

        return ServiceResource::collection($services);
    }

    public function show(Request $request, Service $service): ServiceResource|JsonResponse
    {
        if ($service->user_id !== $request->user()->id) {
            return response()->json(['message' => 'Forbidden.'], 403);
        }

        $service->load('plan:id,name,price,billing_cycle');

        return new ServiceResource($service);
    }

    public function reboot(Request $request, Service $service): JsonResponse
    {
        if ($service->user_id !== $request->user()->id) {
            return response()->json(['message' => 'Forbidden.'], 403);
        }

        if ($service->service_type !== 'vps') {
            return response()->json([
                'message' => 'Reboot is only available for VPS services.',
            ], 422);
        }

        if ($service->status !== 'active') {
            return response()->json([
                'message' => 'Service must be active to reboot.',
            ], 422);
        }

        try {
            $virtfusion = app(VirtFusionService::class);
            $success = $virtfusion->restart($service);

            if ($success) {
                return response()->json([
                    'message' => 'VPS reboot initiated successfully.',
                ]);
            }

            return response()->json([
                'message' => 'Failed to reboot VPS. Please try again.',
            ], 500);
        } catch (\Exception $e) {
            Log::error('API VPS reboot error', [
                'service_id' => $service->id,
                'error' => $e->getMessage(),
            ]);

            return response()->json([
                'message' => 'An error occurred while rebooting the VPS.',
            ], 500);
        }
    }
}
