<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\Log;

use App\Events\Matrix\Factory as MatrixEventFactory;
use App\Events\Matrix\Message;

final class MatrixController extends Controller
{
	private const LOGKEY = 'CMC';

	public function webhook(Request $request): mixed
	{
		$event = MatrixEventFactory::make(Arr::get($request->events,0,[]));

		// Catch our messages that we've posted
		if (($event instanceof Message) && preg_match('#^.*\^[0-9]+_[0-9]+/[0-9]+(\.[0-9]+)?:#',$event->sender)) {
			Log::info(sprintf('%s:- Ignoring Matrix Message event, probably from us [%s]',static::LOGKEY,$event->sender));
			return response(['result'=>'OK']);
		}

		Log::info(sprintf('%s:- Dispatching Matrix Event [%s]',static::LOGKEY,get_class($event)));
		event($event);

		return response(['result'=>'OK']);
	}
}