<?php

namespace Modules\VetOneDemo\Http\Controllers;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

/**
 * Post-registration onboarding gate. Presents two OPTIONAL integrations —
 * WhatsApp (QR pairing) and a Groq API key — then lets the owner into the
 * dashboard. Skipping is always allowed; if Groq is skipped, AI features stay
 * gracefully "not configured" until the owner adds a key later in AI settings.
 */
class OnboardingController extends Controller
{
    public function index(Request $request)
    {
        $businessId = Auth::user()->business_id ?? null;

        return view('vetonedemo::onboarding', [
            'tps'          => config('vetonedemo.tps', []),
            'provisioned'  => session('demo_provisioned'),
            'waConfigured'   => $this->waConfigured($businessId),
            'groqConfigured' => $this->groqConfigured($businessId),
        ]);
    }

    /**
     * Best-effort inline save of a Groq key into the tenant's PRIMARY AI provider
     * slot so AI works immediately. Guarded — a failure just leaves AI off
     * (skippable by design) and never blocks onboarding.
     */
    public function saveGroq(Request $request)
    {
        $request->validate(['api_key' => 'required|string|max:255']);
        $businessId = Auth::user()->business_id ?? null;

        try {
            $model = 'Modules\\AiCore\\Entities\\AiProvider';
            if ($businessId && class_exists($model)) {
                $model::updateOrCreate(
                    ['business_id' => $businessId, 'name' => 'default'],
                    [
                        'provider' => 'openai_compatible',
                        'base_url' => 'https://api.groq.com/openai/v1',
                        'model'    => 'llama-3.3-70b-versatile',
                        'api_key'  => $request->input('api_key'),
                        'enabled'  => 1,
                    ]
                );
                return back()->with('success', __('Groq connected — AI features are now active for your demo.'));
            }
        } catch (\Throwable $e) {
            Log::warning('VetOneDemo onboarding saveGroq failed: ' . $e->getMessage());
        }

        return back()->with('error', __('Could not save the key automatically. You can add it any time in AI settings.'));
    }

    public function skip()
    {
        return $this->finish();
    }

    public function finish()
    {
        session()->forget('demo_provisioned');
        session()->put('vetone_onboarded', true);

        return redirect('/home')->with('status', [
            'success' => 1,
            'msg'     => __('Welcome to your VetOne demo! It is active for the next 48 hours.'),
        ]);
    }

    /* ─────────────────────────── helpers ──────────────────────────────── */

    protected function waConfigured(?int $businessId): bool
    {
        if (! $businessId) {
            return false;
        }
        try {
            return DB::table('wa_channels')
                ->where('business_id', $businessId)
                ->where('status', 'active')
                ->exists();
        } catch (\Throwable) {
            return false;
        }
    }

    protected function groqConfigured(?int $businessId): bool
    {
        if (! $businessId) {
            return false;
        }
        try {
            return DB::table('ai_providers')
                ->where('business_id', $businessId)
                ->whereNotNull('api_key')
                ->where('api_key', '!=', '')
                ->exists();
        } catch (\Throwable) {
            return false;
        }
    }
}
