<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Str;

class WebhookSource extends Model
{
    protected $fillable = [
        'name',
        'type',
        'webhook_token',
        'secret_key',
        'is_active',
        'field_mapping',
        'settings',
    ];

    protected $casts = [
        'is_active' => 'boolean',
        'field_mapping' => 'array',
        'settings' => 'array',
    ];

    protected static function booted()
    {
        static::creating(function ($webhookSource) {
            if (empty($webhookSource->webhook_token)) {
                $webhookSource->webhook_token = Str::random(32);
            }
        });
    }

    public function logs()
    {
        return $this->hasMany(WebhookLog::class);
    }

    public function webhookLogs()
    {
        return $this->hasMany(WebhookLog::class);
    }

    /**
     * Get the full webhook URL
     */
    public function getWebhookUrlAttribute()
    {
        return route('webhook.generic', ['token' => $this->webhook_token]);
    }

    /**
     * Get recent successful webhooks
     */
    public function recentSuccess($limit = 10)
    {
        return $this->logs()
            ->where('status', 'success')
            ->latest()
            ->limit($limit)
            ->get();
    }

    /**
     * Get recent failed webhooks
     */
    public function recentFailures($limit = 10)
    {
        return $this->logs()
            ->where('status', 'failed')
            ->latest()
            ->limit($limit)
            ->get();
    }

    /**
     * Get success rate
     */
    public function getSuccessRateAttribute()
    {
        $total = $this->logs()->count();
        if ($total === 0) {
            return 0;
        }

        $successful = $this->logs()->where('status', 'success')->count();
        return round(($successful / $total) * 100, 2);
    }

    /**
     * Check if this is a WhatsApp webhook
     */
    public function isWhatsAppWebhook(): bool
    {
        return $this->type === 'whatsapp';
    }

    /**
     * Get type label with icon
     */
    public function getTypeLabelAttribute(): string
    {
        return match($this->type) {
            'whatsapp' => '📱 WhatsApp Notification',
            'stripe' => 'Stripe',
            'paypal' => 'PayPal',
            'payment_form' => 'Payment Form',
            'generic' => 'Generic Webhook',
            default => ucfirst($this->type),
        };
    }
}
