<?php

use App\Http\Controllers\OIDCController;
use App\Livewire\ConsentScreen;
use App\Livewire\ManageAuthenticationTokens;
use App\Livewire\ManageUsers;
use App\Livewire\Settings\Appearance;
use App\Livewire\Settings\Password;
use App\Livewire\Settings\Profile;
use App\Mail\InvitationMail;
use App\Models\User;
use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken;
use Illuminate\Support\Facades\Route;
use Illuminate\Support\Facades\Storage;

Route::get('/', function () {
    return view('welcome');
})->name('home');

Route::view('dashboard', 'dashboard')
    ->middleware(['auth', 'verified'])
    ->name('dashboard');

Route::get('admin/users', ManageUsers::class)
    ->middleware(['auth', 'can:viewAny,App\Models\User'])
    ->name('admin.users');

Route::get('tokens', ManageAuthenticationTokens::class)
    ->middleware(['auth'])
    ->name('tokens');

Route::middleware(['auth'])->group(function () {
    Route::redirect('settings', 'settings/profile');

    Route::get('settings/profile', Profile::class)->name('settings.profile');
    Route::get('settings/password', Password::class)->name('settings.password');
    Route::get('settings/appearance', Appearance::class)->name('settings.appearance');
});

Route::get('avatars/{path}', function (string $path) {
    $path = Storage::disk('avatars')->path($path);

    return response()->file($path);
})->name('user.avatar');

// OIDC Endpoints
Route::prefix('application/o')->group(function () {
    Route::get('authorize', [OIDCController::class, 'authorize'])->middleware('auth')->name('auth.authorize');
    Route::post('token', [OIDCController::class, 'token'])->withoutMiddleware(VerifyCsrfToken::class)->name('auth.token');
    Route::get('userinfo', [OIDCController::class, 'userinfo'])->name('auth.userinfo');
    Route::get('confirm', ConsentScreen::class)->name('auth.confirm');
    Route::get('logout', [OIDCController::class, 'logout'])->name('auth.logout');
});
Route::get('.well-known/jwks.json', [OIDCController::class, 'jwks'])->name('auth.keys');
Route::get('.well-known/openid-configuration', [OIDCController::class, 'openidConfig'])->name('auth.openid-configuration');

// Test route for invitation email preview
Route::get('/test-invitation-email', function () {
    $invitation = new \App\Models\Invitation([
        'email' => 'test@example.com',
        'code' => 'test-invitation-code-123',
        'expires_at' => now()->addDays(7),
        'invited_by' => 1,
    ]);

    return new \App\Mail\InvitationMail($invitation);
})->middleware('auth');

require __DIR__ . '/auth.php';
