<?php

namespace App\Http\Controllers\Api\Settings;

use App\Domains\AI\Models\AiKnowledgeSnippet;
use App\Http\Controllers\Controller;
use App\Http\Requests\AI\StoreKnowledgeSnippetRequest;
use Illuminate\Http\JsonResponse;

class AiKnowledgeSnippetController extends Controller
{
    public function index(): JsonResponse
    {
        return response()->json([
            'data' => AiKnowledgeSnippet::query()
                ->where('tenant_id', request()->user()->tenant_id)
                ->latest()
                ->get(),
        ]);
    }

    public function store(StoreKnowledgeSnippetRequest $request): JsonResponse
    {
        $data = $request->validated();

        $snippet = AiKnowledgeSnippet::query()->create([
            ...$data,
            'tenant_id' => $request->user()->tenant_id,
            'status' => $data['status'] ?? 'active',
        ]);

        return response()->json([
            'data' => $snippet,
        ], 201);
    }

    public function update(StoreKnowledgeSnippetRequest $request, string $snippet): JsonResponse
    {
        $record = $this->snippet($snippet);
        $record->update($request->validated());

        return response()->json([
            'data' => $record->fresh(),
        ]);
    }

    public function destroy(string $snippet): JsonResponse
    {
        $this->snippet($snippet)->delete();

        return response()->json(status: 204);
    }

    protected function snippet(string $id): AiKnowledgeSnippet
    {
        return AiKnowledgeSnippet::query()
            ->where('tenant_id', request()->user()->tenant_id)
            ->findOrFail($id);
    }
}
