<?php

namespace App\Models;

use App\Models\Concerns\BelongsToTenant;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Support\Str;

class Webhook extends Model
{
    use BelongsToTenant;

    protected $fillable = [
        'name', 'uuid', 'secret', 'default_status', 'duplicate_handling',
        'success_redirect_url', 'is_active', 'total_received',
        'last_triggered_at', 'user_id',
    ];

    protected $hidden = ['secret'];

    protected $casts = [
        'is_active'         => 'boolean',
        'total_received'    => 'integer',
        'last_triggered_at' => 'datetime',
    ];

    protected static function booted(): void
    {
        static::creating(function (Webhook $webhook) {
            $webhook->uuid ??= (string) Str::uuid();
        });
    }

    public function lists(): BelongsToMany
    {
        return $this->belongsToMany(ContactList::class, 'webhook_list', 'webhook_id', 'list_id');
    }

    public function tags(): BelongsToMany
    {
        return $this->belongsToMany(Tag::class, 'webhook_tag', 'webhook_id', 'tag_id');
    }

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

    public function receiveUrl(): string
    {
        return url("/api/webhooks/receive/{$this->uuid}");
    }
}
