<?php

namespace App\Http\Controllers\Admin;

use App\Enums\UserStatus;
use App\Http\Controllers\Controller;
use App\Models\User;
use App\Services\AuditLogger;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\View\View;

class UserController extends Controller
{
    public function __construct(private AuditLogger $auditLogger) {}

    public function index(Request $request): View
    {
        $users = User::query()
            ->with('playerProfile')
            ->when($request->filled('q'), function ($query) use ($request) {
                $term = $request->string('q')->toString();
                $query->where(function ($inner) use ($term) {
                    $inner->where('name', 'like', "%{$term}%")
                        ->orWhere('username', 'like', "%{$term}%")
                        ->orWhere('email', 'like', "%{$term}%");
                });
            })
            ->when($request->filled('status'), fn ($query) => $query->where('status', $request->string('status')))
            ->latest()
            ->paginate(20)
            ->withQueryString();

        return view('admin.users.index', compact('users'));
    }

    public function show(User $user): View
    {
        $user->load(['playerProfile', 'eventRegistrations.event']);

        return view('admin.users.show', compact('user'));
    }

    public function suspend(User $user): RedirectResponse
    {
        $this->authorize('suspend', $user);

        $old = $user->only(['status']);
        $user->update(['status' => UserStatus::Suspended]);
        $this->auditLogger->log('user.suspended', $user, $old, $user->only(['status']));

        return back()->with('success', __('admin.users.suspended_success'));
    }

    public function reactivate(User $user): RedirectResponse
    {
        $this->authorize('suspend', $user);

        $old = $user->only(['status']);
        $user->update(['status' => UserStatus::Active]);
        $this->auditLogger->log('user.reactivated', $user, $old, $user->only(['status']));

        return back()->with('success', __('admin.users.reactivated_success'));
    }
}
