<?php

namespace App\Http\Controllers;

use App\Jobs\AnonymizeAccount;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Str;

class ProfileAccountController extends Controller
{
    public function destroy(Request $request): RedirectResponse
    {
        $confirmationWord = Str::upper(__('profile.delete.confirmation_keyword'));

        $request->validate([
            'confirmation' => [
                'required',
                function ($attribute, $value, $fail) use ($confirmationWord) {
                    if (Str::upper(trim((string) $value)) !== $confirmationWord) {
                        $fail(__('profile.delete.validation', ['word' => $confirmationWord]));
                    }
                },
            ],
        ]);

        $user = $request->user();

        abort_unless($user, 403);

        if ($user->tenant?->anonymized_at) {
            return back()->with('status', __('profile.delete.already'));
        }

        AnonymizeAccount::dispatch($user->id);

        return redirect()->route('profile.index')->with('status', __('profile.delete.started'));
    }
}
