<?php

namespace App\Http\Controllers;

use App\Http\Requests\Auth\UpdatePasswordRequest;
use App\Models\User;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;

class UsersController extends Controller
{
    public function show(User $user)
    {
        return response()->json(
            [
                'id' => $user->id,
                'username' => $user->username,
                'role' => $user->role,
                'avatar_uri' => $user->avatar_uri,
                'level' => $user->level,
                'xp' => $user->xp,
            ]
        );
    }

    public function leaderboard()
    {
        return User::orderBy('xp', 'desc')->get();
    }

    public function updateAvatar(Request $request, User $user)
    {
        if ($request->user()->id !== $user->id) {
            return response()->json(['message' => 'Unauthorized'], 403);
        }

        $request->validate([
            'avatar' => ['required', 'image', 'max:2048'], // 2MB max
        ]);

        $filename = \Illuminate\Support\Str::uuid().'.jpg';
        $path = $request->file('avatar')->storeAs('avatars', $filename, 'public');

        $user->update([
            'avatar_uri' => $path,
        ]);

        return response()->json([
            'message' => 'Avatar updated successfully',
            'avatar_uri' => $user->avatar_uri,
        ]);
    }

    /**
     * @requestMediaType multipart/form-data
     */
    public function updateUsername(Request $request)
    {
        $user = $request->user();

        $request->validate([
            'username' => ['required', 'string','min:3', 'max:30', 'regex:/^[A-Za-z0-9._]+$/'],
        ]);

        $user->update([
            'username' => $request->username,
        ]);

        return response()->json([
            'message' => 'Pseudo updated successfully',
            'username' => $user->username,
        ]);
    }

    /**
     * @requestMediaType multipart/form-data
     */
    public function updatePassword(UpdatePasswordRequest $request)
    {
        $data = $request->validated();
        $user = $request->user();

        if (! Hash::check($data['old_password'], $user->password)) {
            return response()->json([
                'message' => 'The provided password does not match your current password.',
            ], 422);
        }

        $user->update([
            'password' => $data['new_password'],
        ]);

        return response()->json([
            'message' => 'Password updated successfully',
        ]);
    }

    public function softDeleteById(Request $request, User $user): JsonResponse
    {
        if ($user->trashed()) {
            return response()->json([
                'message' => 'User already soft deleted.',
            ], 409);
        }

        $user->delete();

        return response()->json([
            'message' => __('auth.soft_delete_success'),
        ]);
    }
}
