<?php

namespace App\Http\Livewire\WireChat\New;

use Illuminate\Support\Facades\Auth;
use Namu\WireChat\Livewire\New\Chat as NewChat;

class Chat extends NewChat
{
    // This magic accessor will be called for $this->auth
    public function getAuthProperty()
    {
        // Use the active guard from session first, then fallback to checking all guards
        $activeGuard = session('active_guard', 'web');
        $user = Auth::guard($activeGuard)->user();

        if ($user) {
            return $user;
        }

        // Fallback to checking all guards if active guard doesn't have a user
        return Auth::guard('admin')->user()
            ?: Auth::guard('bank')->user()
            ?: Auth::guard('organization')->user()
            ?: Auth::guard('web')->user();
    }

    /**
     * Mount component (override with authorization)
     */
    public function mount()
    {
        // CRITICAL SECURITY: Validate authorization on mount
        $profile = getActiveProfile();
        if (!$profile) {
            abort(403, 'No active profile');
        }
        \App\Helpers\ProfileAuthorizationHelper::authorize($profile);

        return parent::mount();
    }

    public function createConversation($id, string $class)
    {
        // CRITICAL SECURITY: Validate authorization before creating conversation
        $profile = getActiveProfile();
        if (!$profile) {
            abort(403, 'No active profile');
        }
        \App\Helpers\ProfileAuthorizationHelper::authorize($profile);

        $model = app($class);
        $model = $model::find($id);

        if ($model) {

            $createdConversation = $this->auth->createConversationWith($model);

            if ($createdConversation) {
                $this->closeWireChatModal();
                $this->handleComponentTermination(
                    redirectRoute: route(\Namu\WireChat\Facades\WireChat::viewRouteName(), [$createdConversation->id]),
                    events: [
                        \Namu\WireChat\Livewire\Widgets\WireChat::class => ['open-chat',  ['conversation' => $createdConversation->id]],
                    ]
                );
            }
        }
    }
}