<?php

namespace App\Http\Livewire\WireChat\Chats;

use Illuminate\Support\Facades\Auth;
use Namu\WireChat\Livewire\Chats\Chats as BaseChats;

class Chats extends BaseChats
{
    /**
     * Get all listeners including parent's Echo listeners
     */
    public function getListeners()
    {
        // Get parent's listeners (includes Echo channels)
        $parentListeners = parent::getListeners();

        // Debug: Log what listeners are being registered
        \Log::info('WireChat Chats Listeners', [
            'parent_listeners' => $parentListeners,
            'active_guard' => session('active_guard', 'web'),
            'auth_user_id' => $this->auth?->id,
            'auth_user_class' => $this->auth ? get_class($this->auth) : null,
        ]);

        // Add our custom listener
        return array_merge($parentListeners, [
            'refreshList' => 'handleRefreshList',
        ]);
    }

    // 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();
    }


    public function handleRefreshList()
    {
        // Simply dispatch a refresh event to update the component
        $this->dispatch('$refresh');
    }

    /**
     * Override loadConversations to fix lastMessage loading for non-web guards
     * The parent uses auth()->user() which defaults to web guard, causing lastMessage to be null for admin/bank/org guards
     */
    protected function loadConversations()
    {
        // Call parent to load conversations
        parent::loadConversations();

        // Manually load lastMessage for each conversation without global scopes
        // This fixes the issue where WithoutRemovedMessages scope uses auth()->user() (web guard)
        $this->conversations->each(function ($conversation) {
            $lastMessage = \Namu\WireChat\Models\Message::withoutGlobalScopes()
                ->where('conversation_id', $conversation->id)
                ->latest()
                ->first();

            if ($lastMessage) {
                $conversation->setRelation('lastMessage', $lastMessage);
            }
        });
    }

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

        return parent::mount($showNewChatModalButton, $allowChatsSearch, $showHomeRouteButton, $title);
    }

    public function render()
    {
        // CRITICAL SECURITY: Re-validate authorization on every render
        $profile = getActiveProfile();
        if (!$profile) {
            return view('errors.unauthorized-component');
        }

        try {
            \App\Helpers\ProfileAuthorizationHelper::authorize($profile);
        } catch (\Symfony\Component\HttpKernel\Exception\HttpException $e) {
            return view('errors.unauthorized-component');
        }

        return parent::render();
    }
}