<?php

namespace App\Services;

use App\Models\User;
use App\Models\TrustedDevice;
use App\Models\UserLogin;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\Cookie;
use Illuminate\Support\Facades\Auth;
use Jenssegers\Agent\Agent;
use Torann\GeoIP\Facades\GeoIP;

class LoginService
{
      /**
       * Record a login for a user, optionally trusting device
       */
      public function recordLogin(User $user, bool $trustDevice = false, bool $remember = false): void
      {
            if ($trustDevice) {
                  $this->storeTrustedDevice($user);
            }

            $this->storeUserLogin($user);

            // Log in user
            Auth::login($user, $remember);
            session()->regenerate();
      }

      /**
       * Attempt fast-login via trusted device
       */
      public function loginWithTrustedDevice(User $user, bool $remember = false): bool
      {
            $deviceToken = request()->cookie('trusted_device_token');
            if (!$deviceToken)
                  return false;

            $trusted = TrustedDevice::where('user_id', $user->id)
                  ->where('device_token', $deviceToken)
                  ->where('ip_address', request()->ip())
                  ->where('user_agent', request()->header('User-Agent'))
                  ->first();

            if (!$trusted)
                  return false;

            $trusted->update(['last_used_at' => now()]);

            Auth::login($user, $remember);
            session()->regenerate();

            return true;
      }

      /**
       * Store or update a trusted device
       */
      protected function storeTrustedDevice(User $user): void
      {
            $deviceToken = Str::uuid()->toString();
            $fingerprint = hash('sha256', request()->header('User-Agent') . '|' . request()->ip());

            TrustedDevice::updateOrCreate(
                  ['user_id' => $user->id, 'device_fingerprint' => $fingerprint],
                  [
                        'device_token' => $deviceToken,
                        'ip_address' => request()->ip(),
                        'user_agent' => request()->header('User-Agent'),
                        'last_used_at' => now(),
                  ]
            );

            Cookie::queue(
                  Cookie::make(
                        'trusted_device_token',
                        $deviceToken,
                        config('auth.trusted_device_lifetime', 43200),
                        '/',
                        null,
                        true,
                        true,
                        false,
                        'strict'
                  )
            );
      }

      /**
       * Store user login history
       */
      protected function storeUserLogin(User $user): void
      {
            $ip = collect(explode(',', request()->header('X-Forwarded-For') ?? ''))
                  ->map(fn($ip) => trim($ip))
                  ->first(fn($ip) => filter_var($ip, FILTER_VALIDATE_IP))
                  ?? request()->ip();

            $agent = new Agent();

            try {
                  $location = GeoIP::getLocation($ip);
            } catch (\Throwable $e) {
                  $location = null;
            }

            UserLogin::create([
                  'user_id' => $user->id,
                  'ip_address' => $ip,
                  'location' => ($location->city ?? 'Unknown') . ', ' . ($location->country ?? 'Unknown'),
                  'browser' => $agent->browser() ?: 'Unknown',
                  'device' => $agent->device() ?: 'Desktop',
                  'platform' => $agent->platform() ?: 'Unknown',
                  'user_agent' => request()->header('User-Agent'),
                  'login_at' => now(),
            ]);
      }
}