<?php

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
use Illuminate\Support\Facades\DB;
use App\Http\Controllers\ApplicationController;
use App\Http\Controllers\API\UserController;
use App\Http\Controllers\TemplateController;
use App\Models\User;
use Illuminate\Support\Facades\Hash;
/*
|--------------------------------------------------------------------------
| API Routes
|--------------------------------------------------------------------------
|
| Here is where you can register API routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| is assigned the "api" middleware group. Enjoy building your API!
|
*/

Route::middleware('auth:sanctum')->get('/user', function (Request $request) {
    $user = $request->user();
    $islogin = $user->tokenCan('update');
    $test = $islogin ? 'true' : 'false';
    return $user;
});




Route::post('/login', function (Request $request) {
    $data = $request->validate([
        'account' => 'required',
        'password' => 'required'
    ]);

    $user = User::where('account', $request->account)->first();

    if (!$user || !Hash::check($request->password, $user->password)) {
        return response([
            'message' => ['These credentials do not match our records.']
        ], 404);
    }

    $token = $user->createToken('test-token', [$user->role])->plainTextToken;
    $response = [
        'user' => JSON_ENCODE($user, JSON_UNESCAPED_UNICODE),
        'token' => $token,
    ];

    return response($response, 201);
});
Route::post('/logout', function (Request $request) {
    $user = $request->user();
    $user->tokens()->delete();

    return $user;
})->middleware(['auth:sanctum']);

Route::post('/refresh', function (Request $request) {
    $user = $request->user();
    $user->tokens()->delete();

    $token = $user->createToken('test-token', ['uploader', 'tester'])->plainTextToken;

    $response = [
        'user' => $user,
        'token' => $token,
    ];

    return response($response, 201);
})->middleware(['auth:sanctum']);


/* Template API */
Route::post('/index', [TemplateController::class, 'index']);

Route::middleware('auth:sanctum')->group(function () {
    
});

Route::middleware(['auth:sanctum', 'abilities:Admin'])->group(function () {
    
});