<?php

namespace App\Http\Controllers\API;

use App\Entity\Token;
use App\Exceptions\HTTPException;
use App\Exceptions\NotLoggedInException;
use App\Exceptions\ResourceNotFound;
use App\Models\AccessToken;
use App\Models\App;
use App\Models\AppAccess;
use App\Models\AppCode;
use App\Models\RefreshToken;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Log;
use TaGeSo\APIResponse\Response;

class oAuthController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    public function getAccess(Response $response, Request $request, $id) {
        if(!Auth::check()) {
            throw new NotLoggedInException();
        }

        $app = App::query()->where("id", "=", $id);

        if($request->get("create", false)) {
            $access = AppAccess::getOrCreate(Auth::user()->id, $id);
        } else {
            $access = AppAccess::query()
                ->where("user_id", "=", Auth::user()->id)
                ->where("app_id", "=", $id)->first();
        }

        if(empty($access)) {
            throw new ResourceNotFound();
        }

        //Auto Allow
        if($app->auto_accept) {
            $access->status = "allowed";
        }

        return $response->withData(new \App\Http\Resources\API\App($access));
    }
}