<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\EmailConfirmationToken;
use App\Services\EmailConfirmationExecutor;
use Illuminate\Http\RedirectResponse;
use Illuminate\Validation\ValidationException;
use Inertia\Inertia;

class AccrualEmailConfirmationController extends Controller
{
    public function confirm(string $token, EmailConfirmationExecutor $executor): RedirectResponse
    {
        $record = EmailConfirmationToken::findValidByPlain($token);
        if ($record === null) {
            Inertia::flash('toast', [
                'type' => 'error',
                'message' => 'El enlace de acreditación no es válido o expiró.',
            ]);

            return redirect()->route('admin.platform-accrual.index');
        }

        try {
            $count = $executor->fulfillAccrual($record);
        } catch (ValidationException $e) {
            $first = $e->errors()['token'][0] ?? 'No se pudo ejecutar la acreditación.';

            Inertia::flash('toast', [
                'type' => 'error',
                'message' => $first,
            ]);

            return redirect()->route('admin.platform-accrual.index');
        }

        Inertia::flash('toast', [
            'type' => 'success',
            'message' => "Acreditación ejecutada. Operaciones registradas: {$count}.",
        ]);

        return redirect()->route('admin.platform-accrual.index');
    }
}
