<?php

namespace App\Http\Controllers;

use App\Http\Requests\ChangePasswordRequest;
use App\Services\AzerothCoreAccountService;
use App\Services\GameClientDownloadService;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\View\View;
use Throwable;

class CabinetController extends Controller
{
    public function index(Request $request, AzerothCoreAccountService $accounts): View
    {
        $user = $request->user();

        return view('cabinet.index', [
            'user' => $user,
            'characters' => $accounts->charactersForAccount($user->id),
            'clientFilename' => config('moonwell.client.object_key'),
        ]);
    }

    public function updatePassword(ChangePasswordRequest $request, AzerothCoreAccountService $accounts): RedirectResponse
    {
        $user = $request->user();

        if (! $accounts->validatePassword($user, $request->string('current_password')->toString())) {
            return back()->withErrors(['current_password' => 'Текущий пароль указан неверно.']);
        }

        $accounts->updatePassword($user, $request->string('password')->toString());

        return back()->with('status', 'Пароль успешно обновлён.');
    }

    public function client(GameClientDownloadService $clientDownloadService): RedirectResponse
    {
        try {
            return redirect()->away($clientDownloadService->temporaryUrl());
        } catch (Throwable $exception) {
            report($exception);

            return back()->with('error', 'Не удалось получить ссылку на клиент. Попробуй ещё раз позже.');
        }
    }
}
