<?php

namespace App\Notifications;

use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Notifications\Notification;
use Illuminate\Support\Collection;
use App\Models\InventoryAlert;

class LowStockAlert extends Notification implements ShouldQueue
{
    use Queueable;

    protected $items;
    protected $alert;

    /**
     * Create a new notification instance.
     */
    public function __construct(Collection $items, InventoryAlert $alert)
    {
        $this->items = $items;
        $this->alert = $alert;
    }

    /**
     * Get the notification's delivery channels.
     *
     * @return array<int, string>
     */
    public function via(object $notifiable): array
    {
        return ['mail', 'database'];
    }

    /**
     * Get the mail representation of the notification.
     */
    public function toMail(object $notifiable): MailMessage
    {
        $mailMessage = (new MailMessage)
            ->subject('Low Stock Alert - Action Required')
            ->greeting('Hello ' . $notifiable->name . ',')
            ->line('The following items are running low on stock and require your attention:')
            ->line('');

        foreach ($this->items as $item) {
            $mailMessage->line("• {$item->name} (SKU: {$item->sku}) - Current stock: {$item->available_stock}, Minimum required: {$item->min_stock_level}");
        }

        return $mailMessage
            ->line('')
            ->line("These items have fallen below the {$this->alert->low_stock_threshold}% threshold of their minimum stock level.")
            ->action('View Low Stock Items', route('inventory.alerts.low-stock'))
            ->line('Please take appropriate action to replenish these items.');
    }

    /**
     * Get the array representation of the notification.
     *
     * @return array<string, mixed>
     */
    public function toArray(object $notifiable): array
    {
        return [
            'title' => 'Low Stock Alert',
            'message' => count($this->items) . ' items are running low on stock',
            'action_url' => route('inventory.alerts.low-stock'),
            'items' => $this->items->map(function ($item) {
                return [
                    'id' => $item->id,
                    'name' => $item->name,
                    'sku' => $item->sku,
                    'current_stock' => $item->available_stock,
                    'min_stock' => $item->min_stock_level,
                ];
            }),
        ];
    }
}
