<?php

namespace App\Services;

use App\Contracts\Repositories\AdminRepositoryInterface;
use App\Models\Admin;
use Illuminate\Auth\AuthenticationException;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class AdminAuthenticationService
{
    public function __construct(private readonly AdminRepositoryInterface $admins) {}

    public function authenticate(Request $request, string $email, string $password, bool $remember): ?Admin
    {
        $admin = $this->admins->findActiveByEmail($email);

        if ($admin === null || ! Auth::guard('admin')->validate(['email' => $email, 'password' => $password, 'is_active' => true])) {
            throw new AuthenticationException(__('The provided credentials are incorrect.'));
        }

        if ($admin->hasTwoFactorEnabled()) {
            $request->session()->put([
                'admin_2fa_id' => $admin->getKey(),
                'admin_2fa_remember' => $remember,
                'admin_2fa_expires_at' => now()->addMinutes(config('security.two_factor.challenge_lifetime_minutes'))->timestamp,
            ]);

            return $admin;
        }

        $this->completeLogin($request, $admin, $remember);

        return null;
    }

    public function completeLogin(Request $request, Admin $admin, bool $remember): void
    {
        Auth::guard('admin')->login($admin, $remember);
        $request->session()->regenerate();
        $request->session()->put('admin_last_activity', time());
        $admin->forceFill(['last_login_at' => now(), 'last_login_ip' => $request->ip()])->save();
    }
}
