<?php

namespace App\Notifications;

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

class ProviderTokenExpiringNotification extends Notification implements ShouldQueue
{
    use Queueable;

    protected $credential;
    protected $daysUntilExpiry;

    /**
     * Create a new notification instance.
     */
    public function __construct(ProviderCredential $credential, int $daysUntilExpiry = 7)
    {
        $this->credential = $credential;
        $this->daysUntilExpiry = $daysUntilExpiry;
    }

    /**
     * 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
    {
        $providerName = $this->credential->provider_display_name;
        $label = $this->credential->label ?: $providerName;
        $expiryDate = $this->credential->token_expires_at->format('F j, Y \a\t g:i A');
        
        $message = (new MailMessage)
            ->subject("⚠️ {$providerName} Token Expiring Soon")
            ->greeting("Hello {$notifiable->name},")
            ->line("Your {$providerName} integration token is expiring soon.")
            ->line("**Provider:** {$label}")
            ->line("**Expires:** {$expiryDate}")
            ->line("**Days Remaining:** {$this->daysUntilExpiry}");

        if ($this->credential->use_for_ads) {
            $message->line("⚠️ **Important:** This provider is configured for ad campaigns. Expiry may affect your active campaigns.");
        }

        $message->action('Reconnect Provider', route('brand.integrations.index'))
            ->line('To avoid service interruption, please reconnect your account before the token expires.')
            ->line('If you have any questions, please contact our support team.');

        return $message;
    }

    /**
     * Get the array representation of the notification.
     *
     * @return array<string, mixed>
     */
    public function toArray(object $notifiable): array
    {
        return [
            'type' => 'provider_token_expiring',
            'credential_id' => $this->credential->id,
            'provider' => $this->credential->provider,
            'provider_display_name' => $this->credential->provider_display_name,
            'label' => $this->credential->label,
            'expires_at' => $this->credential->token_expires_at,
            'days_until_expiry' => $this->daysUntilExpiry,
            'use_for_ads' => $this->credential->use_for_ads,
            'brand_id' => $this->credential->brand_id,
            'message' => "Your {$this->credential->provider_display_name} token expires in {$this->daysUntilExpiry} days",
        ];
    }
}