<?php

namespace App\Models;

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

class WebhookEndpoint extends Model
{
    protected $table = 'meet_webhook_endpoints';

    protected $fillable = [
        'uuid', 'owner_ref', 'organization_id', 'url', 'secret', 'events', 'is_active',
    ];

    protected function casts(): array
    {
        return [
            'events' => 'array',
            'is_active' => 'boolean',
            'secret' => 'encrypted',
        ];
    }

    protected static function booted(): void
    {
        static::creating(function (WebhookEndpoint $endpoint) {
            if (empty($endpoint->uuid)) {
                $endpoint->uuid = (string) Str::uuid();
            }
        });
    }

    public function getRouteKeyName(): string
    {
        return 'uuid';
    }

    public function organization(): BelongsTo
    {
        return $this->belongsTo(Organization::class, 'organization_id');
    }

    public function subscribesTo(string $event): bool
    {
        $events = $this->events ?? config('meet.webhook_events', []);

        return in_array('*', $events, true) || in_array($event, $events, true);
    }
}
