<?php

namespace Ignite\Core\Database\Seeders;

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

class UserTableSeeder extends AbstractSeeder
{
    /**
     * The name of the data file.
     *
     * @var string
     */
    protected $file = 'core_user.json';

    /**
     * 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($this->file)
        ]);

        /** @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;
                    if (! isset($source['password'])) {
                        $source['password'] = config('core.admin.password');
                    }
                }
                if (isset($source['password'])) {
                    $source['password'] = bcrypt($source['password']);
                }

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