<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\AuditLog;
use App\Models\WhitelistApplication;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Inertia\Inertia;
use Inertia\Response;

class WhitelistController extends Controller
{
    public function index(): Response
    {
        return Inertia::render('Admin/Whitelist/Index', [
            'applications' => WhitelistApplication::query()
                ->with('user:id,name')
                ->latest()
                ->paginate(20),
        ]);
    }

    public function update(Request $request, WhitelistApplication $application): RedirectResponse
    {
        $data = $request->validate([
            'status' => ['required', 'in:approved,rejected'],
        ]);

        $application->update([
            ...$data,
            'reviewed_by' => $request->user()->id,
            'reviewed_at' => now(),
        ]);

        if ($data['status'] === 'approved') {
            $application->user->assignRole('player');
        }

        AuditLog::record('whitelist.'.$data['status'], $application, $data);

        return back()->with('success', 'Application updated.');
    }
}
