<?php

namespace App\Http\Controllers\admin;

use App\Http\Controllers\Controller;
use App\Models\admin\Ia;
use App\Traits\CrudTrait;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Prism\Prism\Enums\Provider;
use Prism\Prism\Facades\Prism;

class IaController extends Controller
{
    use CrudTrait;

    protected string $modelClass = Ia::class;

    public function index(Request $request)
    {
        return $this->getData($request);
    }

    public function store(Request $request)
    {
        return $this->storeData($request);
    }

    public function bulkStore(Request $request)
    {
        return $this->bulkStore($request);
    }

    public function update(Request $request)
    {
        return $this->updateData($request);
    }

    public function bulkUpdate(Request $request)
    {
        return $this->multiUpdate($request);
    }

    public function destroy(Request $request)
    {
        return $this->destroyData($request);
    }

    public function bulkDestory(Request $request)
    {
        return $this->bulkDelete($request);
    }

    public function clone(Request $request)
    {
        return $this->cloneData($request);
    }

    public function export(Request $request)
    {
        return $this->exportData($request);
    }

    public function import(Request $request)
    {
        return $this->importData($request);
    }

    public function upload(Request $request)
    {
        return $this->uploadFile($request);
    }

    public function download(Request $request)
    {
        return $this->downloadFile($request);
    }


    public function chat(Request $request)
    {
        try {
            $response = Prism::text()
                ->using('openai', 'gpt-4o-mini')
                ->withSystemPrompt(
                    "You are an ERP assistant. Answer briefly in French."
                )
                ->withPrompt($request->message)
                ->asText(); // generate() deprecated

            Ia::create([
                'user_id' => request()->user()->id,
                'agent' => 'assistant',
                'prompt' => $request->message,
                'response' => $response->text,
                'model' => $response->meta->model
            ]);

            $data=[
               'user' => request()->user()->name,
                'role' => request()->user()->getRoleNames()[0],
                'agent' => 'assistant',
                'prompt' => $request->message,
                'message' => $response->text,
                'timestamp' => now()
            ];

            return response()->json([
                'data' => $data,
                'success' => true,
                'statusCode' => 200,
            ], 200);
        } catch (\Throwable $e) {
            return response()->json([
                'error' => true,
                'message' => $e->getMessage(),
            ], 500);
        }
    }
}
