<?php

namespace App\Http\Controllers\Additional;

use App\Http\Controllers\Controller;
use App\Services\NotionService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\View\View;

class NotionSearchController extends Controller
{
    /**
     * Notion 검색 페이지 (채팅 UI)
     */
    public function index(Request $request): View|Response
    {
        if ($request->header('HX-Request')) {
            return response('', 200)->header('HX-Redirect', route('additional.notion-search.index'));
        }

        return view('additional.notion-search.index');
    }

    /**
     * AJAX 검색 API
     */
    public function search(Request $request): JsonResponse
    {
        $validated = $request->validate([
            'message' => 'required|string|max:1000',
            'history' => 'nullable|array',
        ]);

        try {
            $service = new NotionService;
            $result = $service->searchWithAi(
                $validated['message'],
                $validated['history'] ?? []
            );

            return response()->json($result);
        } catch (\RuntimeException $e) {
            return response()->json([
                'reply' => $e->getMessage(),
                'debug' => null,
            ]);
        }
    }
}
