<?php

namespace Modules\PortalApi\Entities;

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

class PortalPushSubscription extends Model
{
    protected $table = 'portal_push_subscriptions';

    public const CATEGORIES = ['vaccinations', 'appointments', 'lab', 'marketing'];

    protected $fillable = [
        'owner_id', 'endpoint', 'p256dh_key', 'auth_key',
        'user_agent', 'categories', 'last_used_at', 'last_failed_at',
        'consecutive_failures',
    ];

    protected $casts = [
        'categories'      => 'array',
        'last_used_at'    => 'datetime',
        'last_failed_at'  => 'datetime',
    ];

    public function owner(): BelongsTo
    {
        return $this->belongsTo(PortalOwner::class, 'owner_id');
    }

    /** Format expected by minishlink/web-push: \Minishlink\WebPush\Subscription. */
    public function toWebPushArray(): array
    {
        return [
            'endpoint'        => $this->endpoint,
            'publicKey'       => $this->p256dh_key,
            'authToken'       => $this->auth_key,
            'contentEncoding' => 'aesgcm',
        ];
    }

    /** Shorthand: does this subscription want pushes of this category? */
    public function wantsCategory(string $category): bool
    {
        return in_array($category, $this->categories ?? self::CATEGORIES, true);
    }
}
