<?php

namespace App\Http\Controllers\API\V1;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Password;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;

class AuthPasswordController extends Controller
{
    private function isLocalEnv(): bool
    {
        return app()->environment(['local', 'development', 'testing']);
    }

    /**
     * ✅ Send reset password link
     * Works safely in localhost & production
     */
    public function forgotPassword(Request $request)
    {
        $request->validate([
            'email' => ['required', 'email', 'max:191'],
        ]);

        try {
            $status = Password::sendResetLink(
                $request->only('email')
            );

            if ($status !== Password::RESET_LINK_SENT) {
                return response()->json([
                    'success' => false,
                    'data' => null,
                    'error' => __($status),
                ], 422);
            }

            return response()->json([
                'success' => true,
                'data' => [
                    'message' => 'Password reset link sent to your email ✅',
                ],
                'error' => null
            ], 200);

        } catch (\Throwable $e) {
            // ✅ Local fallback (email failed)
            if (! $this->isLocalEnv()) {
                return response()->json([
                    'success' => false,
                    'data' => null,
                    'error' => 'Unable to send reset link. Please try again later.',
                ], 500);
            }

            // ✅ LOCAL: generate token manually
            $token = Str::random(64);

            DB::table('password_reset_tokens')->updateOrInsert(
                ['email' => $request->email],
                [
                    'token' => Hash::make($token),
                    'created_at' => now(),
                ]
            );

            $resetUrl = config('app.frontend_url')
                ? config('app.frontend_url') . "/reset-password?token={$token}&email={$request->email}"
                : "http://localhost:5173/reset-password?token={$token}&email={$request->email}";

            return response()->json([
                'success' => true,
                'data' => [
                    'message' => 'Reset link generated (local only) ✅',
                    'debug_reset_url' => $resetUrl,
                    'debug_token' => $token,
                ],
                'error' => null
            ], 200);
        }
    }

    /**
     * ✅ Reset password using token + email
     */
    public function resetPassword(Request $request)
    {
        $request->validate([
            'token' => ['required', 'string'],
            'email' => ['required', 'email', 'max:191'],
            'password' => ['required', 'string', 'min:6', 'confirmed'],
        ]);

        $status = Password::reset(
            $request->only(
                'email',
                'password',
                'password_confirmation',
                'token'
            ),
            function ($user) use ($request) {
                $user->password = Hash::make($request->password);
                $user->save();
            }
        );

        if ($status !== Password::PASSWORD_RESET) {
            return response()->json([
                'success' => false,
                'data' => null,
                'error' => __($status),
            ], 422);
        }

        return response()->json([
            'success' => true,
            'data' => [
                'message' => 'Password reset successfully ✅ Please login.',
            ],
            'error' => null
        ], 200);
    }
}
