<?php

namespace Ignite\Core\Database\Seeders;

use Ignite\Core\Entities\User;
use Ignite\Core\Entities\UserGroup;

/**
 * php artisan db:seed --class="Ignite\Core\Database\Seeders\UserGroupsTableSeeder"
 * php artisan module:seed Core
 */
class UserGroupsTableSeeder extends AbstractSeeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        parent::run();

        /* TODO: Create a repository class for UserGroup
        $userGroupRepository = app(UserGroupRepository::class); */
        $strategy = $this->strategy('json', [
            'filepath' => $this->getFilepath('core_user_group.json')
        ]);

        /** @var \Illuminate\Support\Collection $sources */
        $sources = $strategy->run();

        foreach ($sources as $source) {
            try {
                $this->getUserId($source);
                UserGroup::updateOrCreate(
                    [
                        'user_id' => $source['user_id'],
                        'group_id' => $source['group_id'],
                    ],
                    $source
                );
            } catch (\Exception $e) {
                echo json_encode($source) . PHP_EOL;
                echo $e->getMessage() . PHP_EOL;
                continue;
            }
        }
    }

    /**
     * Gets the user id if not provided.
     *
     * @param  array  &$data
     */
    protected function getUserId(array &$data)
    {
        if (isset($data['user_id'])) {
            return;
        }
        if (isset($data['username'])) {
            if ($data['username'] === 'it@brightspot.email') {
                $data['username'] = config('core.admin.email', 'it@brightspot.email');
            }

            $user = User::where('username', $data['username'])->first();
            if ($user) {
                unset($data['username']);
                $data['user_id'] = $user->user_id;
            }
        }
    }
}
