<?php

namespace App\Http\Controllers\Admin\Web;

use App\Http\Controllers\Controller;
use App\Interfaces\UserRepositoryInterface;
use App\Models\User;
use App\Services\AuthService;
use Illuminate\Http\Request;

class AdminWebUserController extends Controller
{
    public function __construct(
        private readonly UserRepositoryInterface $userRepo,
        private readonly AuthService $authService
    ) {}

    public function index(Request $request)
    {
        $search = $request->query('search');
        $users  = $this->userRepo->paginate(30, $search);

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

    public function ban(int $id)
    {
        $user = User::findOrFail($id);

        if ($user->is_admin) {
            return back()->with('error', 'Cannot ban an administrator.');
        }

        $this->userRepo->update($id, ['is_banned' => true]);

        return back()->with('success', "{$user->name} has been banned.");
    }

    public function unban(int $id)
    {
        $user = User::findOrFail($id);
        $this->userRepo->update($id, ['is_banned' => false]);

        return back()->with('success', "{$user->name} has been unbanned.");
    }

    /**
     * Anonymize a user's account from the admin panel.
     * Same effect as the in-app "Delete Account" button — personal data
     * is wiped, but predictions/points/badges remain for leaderboard
     * integrity (Google Play data-deletion compliant soft delete).
     */
    public function destroy(int $id)
    {
        $user = User::findOrFail($id);

        if ($user->is_admin) {
            return back()->with('error', 'Cannot delete an administrator.');
        }

        if ($user->isAnonymized()) {
            return back()->with('error', 'This account is already deleted.');
        }

        $this->authService->deleteAccount($user);

        return back()->with('success', 'User account deleted (personal data anonymized).');
    }
}
