<?php

namespace Modules\SmartStorage\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use Modules\SmartStorage\Entities\Services\OtpService;

/**
 * Opens a time-boxed storage-access session via a one-time code. After verifying,
 * the user is bounced back to whatever file/page they were trying to reach.
 */
class OtpController extends Controller
{
    public function __construct(protected OtpService $otp)
    {
    }

    public function challenge(Request $request)
    {
        $intended = $request->input('intended', url('/'));

        return view('smartstorage::otp.challenge', compact('intended'));
    }

    public function send(Request $request)
    {
        $devCode = $this->otp->start($request);

        return response()->json([
            'success' => true,
            'msg'     => 'A code has been sent.',
            // Surfaced only in non-production to ease testing.
            'dev_code' => $devCode,
        ]);
    }

    public function verify(Request $request)
    {
        $request->validate(['code' => 'required|string']);

        $ok = $this->otp->verify($request, $request->input('code'));

        if ($request->expectsJson()) {
            return response()->json([
                'success'  => $ok,
                'msg'      => $ok ? 'Storage unlocked.' : 'Invalid or expired code.',
                'intended' => $request->input('intended'),
            ]);
        }

        if (!$ok) {
            return back()->withErrors(['code' => 'Invalid or expired code.']);
        }

        return redirect($request->input('intended', url('/')));
    }
}
