<?php

namespace App\Http\Controllers\Player;

use App\Http\Controllers\Controller;
use App\Http\Requests\Player\UpdateProfileRequest;
use App\Models\LinkCode;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Inertia\Inertia;
use Inertia\Response;

class ProfileController extends Controller
{
    public function edit(Request $request): Response
    {
        $user = $request->user();

        return Inertia::render('Player/Profile', [
            'user' => $user->only(['id', 'name', 'email', 'discord_avatar', 'fivem_license']),
            'twoFactorEnabled' => $user->two_factor_confirmed_at !== null,
        ]);
    }

    public function update(UpdateProfileRequest $request): RedirectResponse
    {
        $user = $request->user();
        $data = $request->safe()->only(['name', 'email']);

        if ($password = $request->validated('password')) {
            // Argon2id/Bcrypt via Laravel's hasher (config('hashing.driver'))
            // — replaces the legacy app's unsalted MD5 / plaintext options.
            $data['password'] = Hash::make($password);
        }

        $user->update($data);

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

    public function generateLinkCode(Request $request): RedirectResponse
    {
        $linkCode = LinkCode::generateFor($request->user());

        return back()->with('success', "Your link code is {$linkCode->code} — enter it in-game with /linkucp within 10 minutes.");
    }
}
