<?php

namespace Modules\Auth\Http\Controllers;

use App\Http\Controllers\Controller;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Modules\Auth\Entities\User;
use Modules\Auth\Services\PasswordResetOtpService;

class PasswordResetController extends Controller
{
    public function __construct(
        protected PasswordResetOtpService $passwordResetOtpService
    ) {}

    public function requestOtp(Request $request): JsonResponse
    {
        $validated = $request->validate([
            'email' => ['required', 'string', 'email'],
        ]);

        $user = User::where('email', $validated['email'])->first();

        if ($user) {
            $this->passwordResetOtpService->send($user);
        }

        return response()->json([
            'success' => true,
            'message' => 'Jika e-mel wujud dalam sistem, kod OTP untuk reset kata laluan telah dihantar.',
        ]);
    }

    public function reset(Request $request): JsonResponse
    {
        $validated = $request->validate([
            'email' => ['required', 'string', 'email'],
            'otp' => ['required', 'string', 'digits:6'],
            'password' => ['required', 'string', 'confirmed'],
        ]);

        $user = User::where('email', $validated['email'])->first();

        if (! $user) {
            return response()->json([
                'success' => false,
                'message' => 'Kod OTP tidak sah.',
            ], 422);
        }

        $this->passwordResetOtpService->reset(
            $user,
            $validated['otp'],
            $request->only(['password', 'password_confirmation']),
        );

        return response()->json([
            'success' => true,
            'message' => 'Kata laluan anda telah berjaya ditetapkan semula. Sila log masuk.',
        ]);
    }
}
