<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\ActivityLog;
use App\Models\Port;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class PortController extends Controller
{
    public function index(Request $request): JsonResponse
    {
        $q = Port::query()->where('is_active', true)->with('server:id,name,ip');
        if ($s = $request->string('status')->toString()) $q->where('status', $s);
        if ($search = $request->string('q')->toString()) {
            $q->where(function ($w) use ($search) {
                $w->where('label', 'like', "%{$search}%")->orWhere('service_type', 'like', "%{$search}%");
            });
        }
        $rows = $q->orderBy('server_id')->orderBy('port')->paginate(min(100, max(10, (int) $request->integer('per_page', 20))));
        return response()->json([
            'data' => $rows->items(),
            'meta' => ['current_page' => $rows->currentPage(), 'last_page' => $rows->lastPage(), 'per_page' => $rows->perPage(), 'total' => $rows->total()],
            'summary' => [
                'total' => Port::where('is_active', true)->count(),
                'up' => Port::where('is_active', true)->where('status', 'up')->count(),
                'down' => Port::where('is_active', true)->where('status', 'down')->count(),
                'timeout' => Port::where('is_active', true)->where('status', 'timeout')->count(),
            ],
        ]);
    }

    public function show(Port $port): JsonResponse
    {
        $port->load('server:id,name,ip');
        return response()->json(['data' => $port]);
    }

    public function store(Request $request): JsonResponse
    {
        $data = $request->validate([
            'server_id' => ['required', 'integer', 'exists:servers,id'],
            'label' => ['nullable', 'string', 'max:128'],
            'protocol' => ['required', 'in:tcp,udp,http,https'],
            'port' => ['required', 'integer', 'min:1', 'max:65535'],
            'service_type' => ['nullable', 'string', 'max:64'],
            'expect_banner' => ['nullable', 'boolean'],
            'expected_banner_pattern' => ['nullable', 'string', 'max:255'],
            'alerts_enabled' => ['nullable', 'boolean'],
        ]);
        $data['status'] = 'unknown';
        $port = Port::create($data);
        ActivityLog::log(['action' => 'added port check', 'target' => "{$port->protocol}:{$port->port}", 'subject_type' => Port::class, 'subject_id' => $port->id, 'category' => 'monitoring', 'severity' => 'low']);
        return response()->json(['data' => $port], 201);
    }

    public function update(Request $request, Port $port): JsonResponse
    {
        $data = $request->validate([
            'label' => ['nullable', 'string', 'max:128'],
            'service_type' => ['nullable', 'string', 'max:64'],
            'expect_banner' => ['sometimes', 'boolean'],
            'expected_banner_pattern' => ['nullable', 'string', 'max:255'],
            'is_active' => ['sometimes', 'boolean'],
            'alerts_enabled' => ['sometimes', 'boolean'],
        ]);
        $port->update($data);
        return response()->json(['data' => $port]);
    }

    public function destroy(Port $port): JsonResponse
    {
        $label = "{$port->protocol}:{$port->port}";
        $port->delete();
        ActivityLog::log(['action' => 'deleted port check', 'target' => $label, 'subject_type' => Port::class, 'subject_id' => null, 'category' => 'monitoring', 'severity' => 'medium']);
        return response()->json(['ok' => true]);
    }
}
