<?php

declare(strict_types=1);

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

use App\Http\Controllers\Controller;
use App\Http\Resources\CustomerResource;
use App\Models\AuditLog;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\AnonymousResourceCollection;

class AdminCustomerController extends Controller
{
    /**
     * List all customers (paginated, searchable).
     */
    public function index(Request $request): AnonymousResourceCollection
    {
        $query = User::role('customer')
            ->withCount(['services', 'subscriptions']);

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

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

        $sortBy = $request->input('sort', 'created_at');
        $sortDir = $request->input('direction', 'desc');
        $allowedSorts = ['name', 'email', 'created_at', 'status'];

        if (in_array($sortBy, $allowedSorts, true)) {
            $query->orderBy($sortBy, $sortDir === 'asc' ? 'asc' : 'desc');
        }

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

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

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

    /**
     * Show customer details with service/subscription counts.
     */
    public function show(Request $request, User $user): CustomerResource
    {
        $user->loadCount(['services', 'subscriptions']);

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

        return new CustomerResource($user);
    }
}
