<?php

namespace App\Providers;

use App\Http\Middleware\MongoMiddleware;
use App\Mail\SesConfigurationSetPlugin;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Queue;
use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Facades\Schema;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        Schema::defaultStringLength(191);
        Queue::before(function ($event) {
            if ($event->connectionName === 'sqs' && _env('APP_ENV') == 'staging') {
                fwrite(STDOUT, 'Processing SQS job ID: '.$event->job->getJobId().PHP_EOL);
                fwrite(STDOUT, 'Processing SQS job body: '.$event->job->getRawBody().PHP_EOL);
            }
        });

        if (env('IS_LOCAL') || str_starts_with(config('app.url', ''), 'https://') || in_array(App::environment(), ['production'])) {
            \Illuminate\Support\Facades\URL::forceScheme('https');
        }

        // Automatically add X-SES-CONFIGURATION-SET header to every outgoing email.
        // Works with SMTP (SES SMTP endpoint) — compatible with Symfony Mailer (Laravel 9+)
        $configSet = env('AWS_SES_CONFIGURATION_SET');
        if ($configSet) {
            \Illuminate\Support\Facades\Event::listen(\Illuminate\Mail\Events\MessageSending::class, function ($event) use ($configSet) {
                if (method_exists($event->message, 'getHeaders')) {
                    $event->message->getHeaders()->addTextHeader('X-SES-CONFIGURATION-SET', $configSet);
                }
            });
        }

        // Backward compatibility for Laravel 5.x Blade "or" operator and escaping JSON-LD "@context"
        \Illuminate\Support\Facades\Blade::precompiler(function ($value) {
            $value = preg_replace('/"@context"/', '"@@context"', $value);
            return preg_replace_callback('/(\{\{|\{!!)(.*?)(\}\}|!!\})/s', function ($matches) {
                $content = preg_replace('/\s+or\s+/', ' ?? ', $matches[2]);
                return $matches[1] . $content . $matches[3];
            }, $value);
        });
    }

    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        $this->app->singleton('MongoMiddleware', function ($app) {
            return new MongoMiddleware();
        });
        if(in_array(App::environment(), ['production','staging'])) {
            $this->app->alias('bugsnag.logger', \Illuminate\Contracts\Logging\Log::class);
            $this->app->alias('bugsnag.logger', \Psr\Log\LoggerInterface::class);
        }
    }
}
