<?php

namespace App\Http\Controllers\Meet;

use App\Http\Controllers\Controller;
use App\Http\Controllers\Meet\Concerns\ScopesToAccount;
use App\Models\DirectConversation;
use App\Models\Member;
use App\Services\Meet\DirectMessageService;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\View\View;

class DirectMessageController extends Controller
{
    use ScopesToAccount;

    public function __construct(
        protected DirectMessageService $dms,
    ) {}

    public function index(Request $request): View
    {
        $this->authorizeAbility($request, 'meetings.view');
        $owner = $this->ownerRef($request);
        $organization = $this->organization($request);

        $conversations = DirectConversation::owned($owner)
            ->where('organization_id', $organization->id)
            ->with(['participants', 'messages' => fn ($q) => $q->latest()->limit(1)])
            ->orderByDesc('updated_at')
            ->get();

        $members = Member::owned($owner)
            ->where('organization_id', $organization->id)
            ->where('user_ref', '!=', $owner)
            ->get();

        return view('meet.messages.index', compact('conversations', 'members', 'organization'));
    }

    public function start(Request $request): RedirectResponse
    {
        $this->authorizeAbility($request, 'meetings.view');
        $validated = $request->validate([
            'user_ref' => ['required', 'string', 'max:64'],
        ]);

        $conversation = $this->dms->findOrCreateDm(
            $request->user(),
            $this->organization($request),
            $validated['user_ref'],
        );

        return redirect()->route('meet.messages.show', $conversation);
    }

    public function show(Request $request, DirectConversation $conversation): View
    {
        $this->authorizeAbility($request, 'meetings.view');
        $this->authorizeOwner($request, $conversation);
        abort_unless(
            $conversation->participants()->where('user_ref', $this->ownerRef($request))->exists(),
            403,
        );

        $messages = $conversation->messages()
            ->whereNull('parent_id')
            ->with('replies')
            ->orderBy('created_at')
            ->paginate(50);

        return view('meet.messages.show', compact('conversation', 'messages'));
    }

    public function postMessage(Request $request, DirectConversation $conversation): RedirectResponse
    {
        $this->authorizeOwner($request, $conversation);

        $validated = $request->validate([
            'body' => ['required', 'string', 'max:5000'],
            'parent_id' => ['nullable', 'integer', 'exists:meet_direct_messages,id'],
        ]);

        $this->dms->postMessage(
            $conversation,
            $request->user(),
            $validated['body'],
            $validated['parent_id'] ?? null,
        );

        return back()->with('success', 'Message sent.');
    }
}
