<?php

declare(strict_types=1);

namespace App\Http\Controllers\Api\V1\Admin;

use App\Http\Controllers\Controller;
use App\Http\Resources\AdminServiceResource;
use App\Models\AuditLog;
use App\Models\Service;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\AnonymousResourceCollection;

class AdminServiceController extends Controller
{
    /**
     * List all services (paginated, filterable).
     */
    public function index(Request $request): AnonymousResourceCollection
    {
        $query = Service::query()
            ->with(['user:id,name,email', 'plan:id,name,price,billing_cycle']);

        if ($request->boolean('show_archived')) {
            $query->withTrashed();
        }

        if ($search = $request->input('search')) {
            $query->whereHas('user', function ($q) use ($search): void {
                $q->where('name', 'like', "%{$search}%")
                    ->orWhere('email', 'like', "%{$search}%");
            });
        }

        if ($serviceType = $request->input('service_type')) {
            $query->where('service_type', $serviceType);
        }

        if ($status = $request->input('status')) {
            $query->where('status', $status);
        }

        $perPage = min((int) $request->input('per_page', 15), 100);

        AuditLog::create([
            'admin_id' => $request->user()->id,
            'action' => 'api_list_services',
            'resource_type' => 'service',
            'ip_address' => $request->ip(),
            'user_agent' => $request->userAgent(),
        ]);

        return AdminServiceResource::collection($query->latest()->paginate($perPage));
    }

    /**
     * Show service details.
     */
    public function show(Request $request, Service $service): AdminServiceResource
    {
        $service->load(['user:id,name,email', 'plan:id,name,price,billing_cycle']);

        AuditLog::create([
            'admin_id' => $request->user()->id,
            'action' => 'api_view_service',
            'resource_type' => 'service',
            'resource_id' => $service->id,
            'ip_address' => $request->ip(),
            'user_agent' => $request->userAgent(),
        ]);

        return new AdminServiceResource($service);
    }

    /**
     * Suspend a service.
     */
    public function suspend(Request $request, Service $service): JsonResponse
    {
        if ($service->status === 'suspended') {
            return response()->json([
                'message' => 'Service is already suspended.',
            ], 422);
        }

        $service->update([
            'status' => 'suspended',
            'suspended_at' => now(),
        ]);

        AuditLog::create([
            'user_id' => $service->user_id,
            'admin_id' => $request->user()->id,
            'action' => 'api_suspend_service',
            'resource_type' => 'service',
            'resource_id' => $service->id,
            'ip_address' => $request->ip(),
            'user_agent' => $request->userAgent(),
        ]);

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

        return response()->json([
            'message' => 'Service has been suspended.',
            'data' => new AdminServiceResource($service),
        ]);
    }

    /**
     * Unsuspend a service.
     */
    public function unsuspend(Request $request, Service $service): JsonResponse
    {
        if ($service->status !== 'suspended') {
            return response()->json([
                'message' => 'Service is not suspended.',
            ], 422);
        }

        $service->update([
            'status' => 'active',
            'suspended_at' => null,
        ]);

        AuditLog::create([
            'user_id' => $service->user_id,
            'admin_id' => $request->user()->id,
            'action' => 'api_unsuspend_service',
            'resource_type' => 'service',
            'resource_id' => $service->id,
            'ip_address' => $request->ip(),
            'user_agent' => $request->userAgent(),
        ]);

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

        return response()->json([
            'message' => 'Service has been unsuspended.',
            'data' => new AdminServiceResource($service),
        ]);
    }
}
