<?php

namespace Mtc\Plugins\MembersMessaging\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Routing\Controller;

use Mtc\Modules\Members\Models\Member;
use Mtc\Plugins\MembersMessaging\Models\Thread;
use Mtc\Modules\Members\Classes\Auth;

class MemberMessagesController extends Controller
{
    /**
     * @param Request $request
     * @return RedirectResponse
     */
    public function store(Request $request)
    {
        $validated = $request->validate([
            'text' => 'required|string',
            'url' => 'required|exists:messenger_threads,url'
        ]);

        $thread = Thread::whereUrl($validated['url'])
            ->first();

        if ($thread->isClosedOrArchived()) {
            return response()->json(
                ['message' => 'Thread is closed or archived.'],
                400
            );
        }

        if (!$thread) {
            return response()->json(
                ['message' => 'Thread not found.'],
                400
            );
        }

        $message = $thread->messages()->create([
            'member_id' => Auth::getLoggedInMember()->id,
            'text' => $validated['text'],
        ]);

        return response()->json([
            'data' => $message,
            'message' => "Message has been successfully sent.",
        ], 200);
    }
}
