<?php

namespace Ignite\Core\Database\Seeders;

use Ignite\Core\Entities\Group;
use Ignite\Core\Entities\Permission;

class GroupPermissionTableSeeder extends AbstractSeeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        parent::run();

        $strategy = $this->strategy('json', [
            'filepath' => realpath(__DIR__ . '/../Data/core_group_permission.json')
        ]);

        /** @var \Illuminate\Support\Collection $sources */
        $sources = $strategy->run();
        $permissions = Permission::whereIn('key', $sources->pluck('permission_key')->keys()->toArray())->get()->keyBy('key');

        if ($permissions->isEmpty()) {
            echo 'No permissions were seeded.';
            return;
        }

        foreach ($sources as $source) {
            try {
                /** @var Group $group */
                $groups = Group::whereIn('key', explode('|', $source['group_name']))->get();
                $permission = $permissions[$source['permission_key']];
                foreach ($groups as $group) {
                    $group->givePermissionTo($permission);
                }
            } catch (\Exception $e) {
                echo $e->getMessage() . PHP_EOL;
                continue;
            }
        }
    }
}
