<?php

namespace Ignite\Core\Database\Seeders;

use Illuminate\Database\Eloquent\Model;
use Ignite\Core\Entities\User;

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

        /* TODO: Create a repository class for User
        $userRepository = app(UserRepository::class); */
        $strategy = $this->strategy('json', [
            'filepath' => $this->getFilepath('core_user.json')
        ]);

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

        foreach ($sources as $source) {
            try {
                if ($source['email'] === 'it@brightspot.email') {
                    $source['username'] = $email = config('core.admin.email', 'it@brightspot.email');
                    $source['email'] = $email;
                    $source['password'] = bcrypt(config('core.admin.password'));
                }

                Model::unguarded(function () use ($source) {
                    User::updateOrCreate(
                        ['username' => $source['username']],
                        $source
                    );
                });
            } catch (\Exception $e) {
                echo $e->getMessage() . PHP_EOL;
                continue;
            }
        }
    }
}
