<?php

namespace App\Http\Controllers;

use App\Http\Controllers\Concerns\ResolvesCurrentOrganization;
use Illuminate\Http\Request;
use Illuminate\Support\Str;
use Illuminate\View\View;
use Illuminate\Http\RedirectResponse;

class ChatWidgetController extends Controller
{
    use ResolvesCurrentOrganization;

    public function __invoke(Request $request): View
    {
        $organization = $this->currentOrganization($request);

        return view('chat-widget.show', [
            'organization' => $organization,
            'scriptUrl' => url('/widget.js'),
            'apiUrl' => url('/api/widget/messages'),
        ]);
    }

    public function resetKey(Request $request): RedirectResponse
    {
        $organization = $this->currentOrganization($request);
        
        $organization->forceFill([
            'widget_public_key' => 'wpk_' . Str::random(32),
        ])->save();

        return back()->with('status', 'Widget key has been reset successfully. Existing integrations using the old key will stop working immediately.');
    }
}
