<?php

namespace App\Http\Controllers;

use App\Models\User;
use App\Http\Traits\ResponseTrait;
use App\Repositories\Contracts\UserRepositoryInterface;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Password;
use Illuminate\Http\Request;

class AuthController extends Controller
{
    use ResponseTrait;

    private $userRepository;

    public function __construct(UserRepositoryInterface $userRepository)
    {
        $this->userRepository = $userRepository;
    }

    //
    public function login(Request $request)
    {
        // Validate the request data
        $request->validate([
            'email' => 'required|email',
            'password' => 'required|string|min:6',
        ]);

        // Logic for user authentication
        $user = User::where('email', $request->email)->first();

        if (! $user || ! Hash::check($request->password, $user->password)) {
            return response()->json(['message' => 'Invalid email or password'], 422);
        }

        $token = $user->createToken('mobile-app-token')->plainTextToken;

        return response()->json([
            'user' => $user,
            'token' => $token,
            'message' => 'Login successful'
        ], 200);
        
    }

    public function register(Request $request)
    {
        // Validate the request data
        $request->validate([
            'name' => 'required|string|max:255',
            'email' => 'required|email|unique:users,email',
            'password' => 'required|string|min:6|confirmed',
        ]);

        // Logic for user registration
        $user = $this->userRepository->create([
            'name' => $request->name,
            'email' => $request->email,
            'phone' => $request->phone,
            'username' => $request->username,
            'password' => Hash::make($request->password),
        ]);

        // Assign role
        $user->assignRole($request->role);

        return response()->json(['message' => 'Registration successful'], 201);
    }

    public function logout(Request $request)
    {
        // Logic for user logout
        $request->user()->currentAccessToken()->delete();

        return response()->json(['message' => 'Logout successful'], 200);
    }

    public function refresh(Request $request)
    {
        // Logic for token refresh
        // ...

        return response()->json(['message' => 'Token refreshed successfully'], 200);
    }

    public function user(Request $request)
    {
        // Logic to return authenticated user details
        // ...

        $user = $request->user();
        $user->role = $user->getRoleNames()->first();
        $user->student = $user->studentProfile;
        $user->researcher = $user->researcherProfile;
        $user->recruiter = $user->recruiterProfile;
        $user->learner = $user->learnerProfile;

        return response()->json(['user' => $user], 200);
    }

    public function forgotPassword(Request $request)
    {
        // Validate the request data
        $request->validate([
            'email' => 'required|email|exists:users,email',
        ]);

        // Send password reset link
        $status = Password::sendResetLink(
            $request->only('email')
        );

        if ($status === Password::RESET_LINK_SENT) {
            return $this->successResponse(
                null,
                'Password reset link has been sent to your email address.'
            );
        }

        // Return generic message to prevent email enumeration
        return $this->successResponse(
            null,
            'If the email exists, a password reset link has been sent.'
        );
    }

    public function resetPassword(Request $request)
    {
        // Validate the request data
        $request->validate([
            'token' => 'required|string',
            'email' => 'required|email|exists:users,email',
            'password' => 'required|string|min:6|confirmed',
        ]);

        // Reset password
        $status = Password::reset(
            $request->only('email', 'password', 'password_confirmation', 'token'),
            function ($user, $password) {
                $user->forceFill([
                    'password' => Hash::make($password)
                ])->save();

                // Revoke all user tokens for security
                $user->tokens()->delete();
            }
        );

        if ($status === Password::PASSWORD_RESET) {
            return $this->successResponse(
                null,
                'Password has been reset successfully. You can now login with your new password.'
            );
        }

        return $this->errorResponse(
            'Invalid or expired reset token. Please request a new password reset link.'
        );
    }

    public function verifyEmail(Request $request)
    {
        // Validate the request data
        $request->validate([
            'email' => 'required|email',
            'verification_code' => 'required|string',
        ]);

        // Logic for email verification
        // ...

        return response()->json(['message' => 'Email verified successfully'], 200);

    }

    public function resendVerificationEmail(Request $request)
    {
        // Validate the request data
        $request->validate([
            'email' => 'required|email',
        ]);

        // Logic for resending verification email
        // ...

        return response()->json(['message' => 'Verification email resent successfully'], 200);
    }
}
