<?php

namespace Database\Seeders\Application;

use App\Models\Core\Auth\Role;
use App\Models\Core\Setting\NotificationAudience;
use App\Models\Core\Setting\NotificationChannel;
use App\Models\Core\Setting\NotificationEvent;
use App\Models\Core\Setting\NotificationSetting;
use Database\Seeders\Traits\DisableForeignKeys;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Seeder;

class NotificationSettingsSeeder extends Seeder
{
    use DisableForeignKeys;
    /**
     * Run the database seeders.
     *
     * @return void
     */
    public function run()
    {
        $this->disableForeignKeys();

        $channels = NotificationChannel::query()
            ->where('name', '!=', 'sms')
            ->get()
            ->pluck('name');

        $onlyDatabase = NotificationChannel::query()
            ->where('name',  'database')
            ->get()
            ->pluck('name');

        $onlyMail = NotificationChannel::query()
            ->where('name',  'mail')
            ->get()
            ->pluck('name');

        $roles = Role::query()
            ->where('is_admin', 1)
            ->whereHas('type', function (Builder $query) {
                $query->where('alias', 'app');
            })->get()
            ->pluck('id');

        NotificationSetting::query()->truncate();

        NotificationEvent::all()->map(function ($event) use ($channels, $roles, $onlyDatabase, $onlyMail) {
            $syncChannels = $channels;
            if(in_array($event->name, ['post_created', 'user_reacted', 'post_commented', 'comment_replied'])) {
                $syncChannels = $onlyDatabase;
            }

            if(in_array($event->name, ['user_invitation', 'password_reset', 'user_registered', 'user_create'])) {
                $syncChannels = $onlyMail;
            }
            
            $notification_setting = NotificationSetting::query()->create([
                'notification_event_id' => $event->id,
                'notify_by' => $syncChannels
            ]);

            $notification_setting->audiences()->saveMany([
                new NotificationAudience([
                    'audience_type' => 'roles',
                    'audiences' => $roles
                ])
            ]);
        });
        $this->enableForeignKeys();
    }
}
