<?php

namespace App\Providers;

use Illuminate\Database\Eloquent\Relations\Relation;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\ServiceProvider;
use SocialiteProviders\Manager\SocialiteWasCalled;

class AppServiceProvider extends ServiceProvider
{
    public function register(): void {}

    public function boot(): void
    {
        Relation::morphMap([
            'episode' => \App\Models\Episode::class,
            'anime'   => \App\Models\Anime::class,
        ]);

        \Event::listen(SocialiteWasCalled::class, \SocialiteProviders\Discord\DiscordExtendSocialite::class);

        $this->loadSmtpFromDb();
    }

    private function loadSmtpFromDb(): void
    {
        try {
            if (!\Schema::hasTable('settings')) return;

            $keys = ['mail_host','mail_port','mail_username','mail_password',
                     'mail_from_address','mail_from_name','mail_encryption'];
            $rows = \App\Models\Setting::whereIn('key', $keys)->pluck('value', 'key');

            if ($rows->isEmpty() || !$rows->get('mail_host')) return;

            Config::set('mail.mailers.smtp.host',       $rows->get('mail_host', ''));
            Config::set('mail.mailers.smtp.port',       $rows->get('mail_port', 587));
            Config::set('mail.mailers.smtp.username',   $rows->get('mail_username', ''));
            Config::set('mail.mailers.smtp.password',   $rows->get('mail_password', ''));
            Config::set('mail.mailers.smtp.encryption', $rows->get('mail_encryption', 'tls'));
            Config::set('mail.from.address',            $rows->get('mail_from_address', ''));
            Config::set('mail.from.name',               $rows->get('mail_from_name', config('app.name')));
            Config::set('mail.default', 'smtp');
        } catch (\Throwable) {
            // DB henüz hazır değilse sessizce geç
        }
    }
}
