<?php

namespace Modules\ClinicStaffPortal\Entities;

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

class CsPushSubscription extends Model
{
    protected $table = 'clinic_staff_push_subscriptions';

    /** Notification categories a staff device can opt in/out of. */
    public const CATEGORIES = ['alerts', 'admissions', 'schedule'];

    protected $fillable = [
        'user_id', 'business_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 user(): BelongsTo
    {
        return $this->belongsTo(User::class, 'user_id');
    }

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

    public function wantsCategory(string $category): bool
    {
        return in_array($category, $this->categories ?? self::CATEGORIES, true);
    }
}
