<?php

namespace App\Http\Controllers\AiPortal;

use App\Models\PortalUrl;
use App\Services\AuditLogger;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller;

/**
 * CRUD for the admin-curated URL knowledge base. The drafter reads these
 * rows at reply-generation time and forces the AI to use only the listed
 * URLs verbatim — no more invented /clients/ paths.
 */
class PortalUrlController extends Controller
{
    public function index(Request $request)
    {
        abort_unless($request->user()->isAdminOrAbove(), 403);
        return response()->json([
            'urls'       => PortalUrl::orderBy('sort_order')->orderBy('id')->get(),
            'categories' => PortalUrl::CATEGORIES,
        ]);
    }

    public function store(Request $request)
    {
        abort_unless($request->user()->isAdminOrAbove(), 403);
        $data = $this->validateUrl($request);
        $row = PortalUrl::create([
            ...$data,
            'enabled'    => $data['enabled'] ?? true,
            'created_by' => $request->user()->id,
        ]);
        AuditLogger::log('user', (string) $request->user()->id, $request->user()->email,
            'portal_url.added', 'portal_url', (string) $row->id,
            ['label' => $row->label, 'url' => $row->url], $request);
        return response()->json($row, 201);
    }

    public function update(Request $request, PortalUrl $portal_url)
    {
        abort_unless($request->user()->isAdminOrAbove(), 403);
        $data = $this->validateUrl($request, partial: true);
        $portal_url->fill($data)->save();
        AuditLogger::log('user', (string) $request->user()->id, $request->user()->email,
            'portal_url.updated', 'portal_url', (string) $portal_url->id,
            ['changed' => array_keys($data)], $request);
        return response()->json($portal_url->fresh());
    }

    public function destroy(Request $request, PortalUrl $portal_url)
    {
        abort_unless($request->user()->isAdminOrAbove(), 403);
        AuditLogger::log('user', (string) $request->user()->id, $request->user()->email,
            'portal_url.removed', 'portal_url', (string) $portal_url->id,
            ['label' => $portal_url->label], $request);
        $portal_url->delete();
        return response()->noContent();
    }

    private function validateUrl(Request $request, bool $partial = false): array
    {
        $required = $partial ? 'nullable' : 'required';
        return $request->validate([
            'label'      => [$required, 'string', 'max:128'],
            'url'        => [$required, 'url', 'max:500'],
            'purpose'    => [$required, 'string', 'max:2000'],
            'category'   => ['nullable', 'string', 'max:32'],
            'enabled'    => ['nullable', 'boolean'],
            'sort_order' => ['nullable', 'integer', 'between:0,9999'],
        ]);
    }
}
