<?php

namespace App\Services\Auth;

use App\Models\User;
use App\Services\Auth\Contracts\AuthServiceInterface;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class AuthService implements AuthServiceInterface
{
    public function attemptLogin(array $credentials, Request $request): array
    {
        // Manual MD5 password check
        $user = User::where('mail', $credentials['mail'])->first();
        if (!$user || $user->pass !== md5($credentials['password'])) {
            return ['success' => false, 'error_key' => 'mail', 'error_msg' => 'Thông tin đăng nhập không đúng. Vui lòng nhập lại'];
        }

        // Log the user in manually
        Auth::login($user);
        $request->session()->regenerate();
        if ($user->status != config('constants.STATUS_ACTIVE')) {
            Auth::logout();
            return ['success' => false, 'error_key' => 'permission', 'error_msg' => 'Bạn không có quyền truy cập. Vui lòng liên hệ quản trị viên'];
        }

        return ['success' => true, 'user' => $user];
    }

    public function logout(Request $request): void
    {
        Auth::logout();
        $request->session()->invalidate();
        $request->session()->regenerateToken();
    }

    public function getRedirectRouteForUser(User $user): string
    {
        if ($user->role == config('constants.ROLE_ADMIN')) {
            return route('admin.dashboard');
        }

        if ($user->first_login == config('constants.FIRST_LOGIN_TRUE')) {
            return route('user.change_password');
        }

        return route('user.dashboard');
    }

    public function forgotPassword(string $email): array
    {
        $email = \Illuminate\Support\Str::lower(trim($email));
        $user = User::where('mail', $email)->first();

        if (!$user) {
            return ['success' => false, 'error_msg' => config('constants.MSG_FORGOT_PWD_EMAIL_NOT_FOUND')];
        }

        if ($user->status != config('constants.STATUS_ACTIVE')) {
            return ['success' => false, 'error_msg' => config('constants.MSG_FORGOT_PWD_ACCOUNT_INACTIVE')];
        }

        // Generate random password (8 characters)
        $newPassword = \Illuminate\Support\Str::random(8);

        // Update password with md5 and set first_login flag to 1
        $user->pass = md5($newPassword);
        $user->first_login = config('constants.FIRST_LOGIN_TRUE');
        $user->save();

        // Send Email
        try {
            \Illuminate\Support\Facades\Mail::to($user->mail)->send(new \App\Mail\ResetPasswordMail($user, $newPassword));
        } catch (\Exception $e) {
            \Illuminate\Support\Facades\Log::error('Failed to send reset password email: ' . $e->getMessage());
            return ['success' => false, 'error_msg' => config('constants.MSG_FORGOT_PWD_MAIL_FAILED')];
        }

        return ['success' => true, 'message' => config('constants.MSG_FORGOT_PWD_SUCCESS')];
    }
}