<?php

namespace Modules\AiCore\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use Modules\AiCore\Entities\AiFeedback;

/**
 * Records AI-suggestion feedback events (the audit trail). Called by the AI UI
 * widgets when a suggestion is generated and when it is applied/dismissed, so the
 * usage dashboard can report an acceptance rate. Pure telemetry — always returns
 * success and never affects the user's flow.
 */
class AiFeedbackController extends Controller
{
    public function store(Request $request)
    {
        $data = $request->validate([
            'module'  => 'nullable|string|max:60',
            'feature' => 'nullable|string|max:80',
            'action'  => 'required|string|in:generated,applied,accepted,rejected,dismissed',
            'meta'    => 'nullable|array',
        ]);

        // Robust against middleware order: prefer the authenticated user's business.
        $businessId = (int) (optional(auth()->user())->business_id
            ?? $request->session()->get('user.business_id'));

        if ($businessId) {
            AiFeedback::record($businessId, $data);
        }

        return response()->json(['success' => true]);
    }
}
