<?php

namespace App\Http\Controllers\Admin\Api;

use App\Http\Controllers\Controller;
use App\Models\IpAddress;
use App\Models\IpPool;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class IpAddressApiController extends Controller
{
    public function records(Request $request, IpPool $pool): JsonResponse
    {
        $query = $pool->ipAddresses()->with('clientProduct');

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

        if (! empty($request->input('search.value'))) {
            $term = $request->input('search.value');
            $query->where(function ($q) use ($term) {
                $q->where('address', 'like', "%{$term}%")
                    ->orWhere('rdns_record', 'like', "%{$term}%")
                    ->orWhere('notes', 'like', "%{$term}%");
            });
        }

        $total = $query->count();
        $start = (int) $request->input('start', 0);
        $length = (int) $request->input('length', 10);

        $rows = $query->orderBy('address_long')->skip($start)->take($length)->get();

        $data = $rows->map(function (IpAddress $ip) {
            return [
                'id' => $ip->id,
                'address' => $ip->address,
                'status' => $ip->status,
                'client_product_id' => $ip->client_product_id,
                'client_product_label' => $ip->client_product_id ? "#{$ip->client_product_id}" : '—',
                'assigned_at' => optional($ip->assigned_at)->format('Y-m-d H:i'),
                'released_at' => optional($ip->released_at)->format('Y-m-d H:i'),
                'rdns_record' => $ip->rdns_record,
                'allocated_via' => $ip->allocated_via,
                'notes' => $ip->notes,
            ];
        })->values()->toArray();

        return response()->json([
            'draw' => (int) $request->input('draw', 1),
            'recordsTotal' => $total,
            'recordsFiltered' => $total,
            'data' => $data,
        ]);
    }
}
