<?php

namespace App\Http\Controllers\Authentication;

use App\Http\Controllers\Controller;
use App\Repositories\Auth\BiodataRepository;
use App\Repositories\Auth\EmailRepository;
use App\Repositories\Auth\IsdmRepository;
use App\Repositories\Auth\RoleRepository;
use App\Repositories\Auth\SsoRepository;
use App\Repositories\Auth\UserRepository;
use App\Repositories\UserdetailRepository;
use Auth;
use Illuminate\Support\Str;

class LoginController extends Controller
{
    private $ssoRepo;
    private $userRepo;
    private $roleRepo;
    private $biodataRepo;
    private $emailRepo;
    private $isdmRepo;
    private $userDetailRepo;

    public function __construct(
        SsoRepository $ssoRepo,
        UserRepository $userRepo,
        RoleRepository $roleRepo,
        BiodataRepository $biodataRepo,
        EmailRepository $emailRepo,
        IsdmRepository $isdmRepo,
        UserdetailRepository $userDetailRepo
    ) {
        $this->middleware('guest');
        $this->ssoRepo = $ssoRepo;
        $this->userRepo = $userRepo;
        $this->roleRepo = $roleRepo;
        $this->biodataRepo = $biodataRepo;
        $this->emailRepo = $emailRepo;
        $this->isdmRepo = $isdmRepo;
        $this->userDetailRepo = $userDetailRepo;
    }

    public function sso($email, $session_id)
    {
        $auth = $this->ssoRepo->sso($session_id);

        if (!is_array($auth)) {
            return redirect('https://sso.unesa.ac.id/user');
        }

        $user = $this->userRepo->find(null, null, $auth[0]->email);

        if ($user) {
            return $this->getlogin($user->id);
        } else {
            return $this->getadduser($auth);
        }
    }

    private function getlogin($id)
    {
        Auth::loginUsingId($id);

        return redirect()->intended('dashboard');
    }

    private function getAdduser($auth)
    {
        $id = (string) Str::uuid();

        $biodata = $this->biodataRepo->biodata($auth);
        $user = $this->userRepo->storeSso($id, $biodata);
        $roles = $this->roleRepo->roles($biodata['role']);
        $this->userDetailRepo->storeSso($user->id, $biodata);
        $this->roleRepo->store($user, $roles);

        Auth::loginUsingId($id);

        return redirect()->intended('dashboard');
    }
}
