<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Controllers\LtiAuthBaseController;
use App\Helpers\DataStructure\OnLaunchData;
use \Illuminate\Contracts\View\View;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Log;
use App\Models\User;
use App\Models\CertConfig;
use App\Models\IssuedCert;

class AppStartController extends LtiAuthBaseController
{
    public function onLaunch(OnLaunchData $data) {
        $user = $data->user;
        Auth::login($user);
        $routeParams = ['resourceLinkId' => $data->resourceLink->id];
        if($user->can('manageCertConfigs', CertConfig::class)){
            Log::debug('[AppStartController] User join in manageCertConfigs');
            return redirect()->route('cert.config', $routeParams);
        }else if ($user->can('viewCertIssuedList', IssuedCert::class)){
            Log::debug('[AppStartController] User join in viewCertIssuedList');
            return redirect()->route('cert.issuedList', $routeParams);
        }else if ($user->can('obtainACert', IssuedCert::class)){
            Log::debug('[AppStartController] User join in viewCertIssuedList');
            return redirect()->route('cert.build', $routeParams);
        }else{
            Log::emergency('[AppStartController] Role not supported for launch this LTI',
            ['roles' => $user->roles]);
            return View('errors.role_not_supported');
        }
    }
}
