<?php

declare(strict_types=1);

namespace App\Notifications;

use App\Models\LoginHistory;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Notifications\Notification;

class NewDeviceLoginNotification extends Notification implements ShouldQueue
{
    use Queueable;

    public function __construct(
        public LoginHistory $loginHistory,
    ) {}

    /** @return array<int, string> */
    public function via(object $notifiable): array
    {
        return ['mail', 'database'];
    }

    public function toMail(object $notifiable): MailMessage
    {
        $location = $this->formatLocation();
        $deviceInfo = $this->formatDeviceInfo();
        $profileUrl = 'https://'.config('app.domains.account').'/profile';

        return (new MailMessage)
            ->subject('New sign-in to your EZSCALE account')
            ->greeting("Hello {$notifiable->name}!")
            ->line("We noticed a new sign-in to your account from a device we don't recognize.")
            ->line("**Device:** {$deviceInfo}")
            ->line("**Location:** {$location}")
            ->line("**IP Address:** {$this->loginHistory->ip_address}")
            ->line('If this was you, you can safely ignore this email. If you did not sign in, please change your password immediately and enable two-factor authentication.')
            ->action('Review Account Security', $profileUrl)
            ->line('Thank you for choosing EZSCALE!');
    }

    /** @return array<string, mixed> */
    public function toArray(object $notifiable): array
    {
        return [
            'type' => 'new_device_login',
            'login_history_id' => $this->loginHistory->id,
            'ip_address' => $this->loginHistory->ip_address,
            'browser' => $this->loginHistory->browser,
            'os' => $this->loginHistory->os,
            'device_type' => $this->loginHistory->device_type,
            'location' => $this->formatLocation(),
            'message' => "New sign-in from {$this->formatDeviceInfo()} ({$this->formatLocation()})",
        ];
    }

    private function formatDeviceInfo(): string
    {
        $parts = array_filter([
            $this->loginHistory->browser,
            $this->loginHistory->os,
        ]);

        if (empty($parts)) {
            return 'Unknown device';
        }

        return implode(' on ', $parts);
    }

    private function formatLocation(): string
    {
        $parts = array_filter([
            $this->loginHistory->location_city,
            $this->loginHistory->location_country,
        ]);

        if (empty($parts)) {
            return $this->loginHistory->ip_address;
        }

        return implode(', ', $parts);
    }
}
