<?php

namespace Modules\Bms\Entities;

use Illuminate\Database\Eloquent\Model;

/** A web-push subscription for a BMS PWA (employee or client). */
class BmsPushSubscription extends Model
{
    protected $table = 'bms_push_subscriptions';

    protected $fillable = [
        'business_id', 'guard', 'subject_id', 'endpoint', 'endpoint_hash',
        'p256dh', 'auth', 'ua', 'last_used_at',
    ];

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

    /** Upsert a subscription by its endpoint hash. */
    public static function store(int $businessId, string $guard, int $subjectId, array $sub, ?string $ua = null): self
    {
        $endpoint = $sub['endpoint'] ?? '';
        return static::updateOrCreate(
            ['endpoint_hash' => hash('sha256', $endpoint)],
            [
                'business_id' => $businessId,
                'guard'       => $guard,
                'subject_id'  => $subjectId,
                'endpoint'    => $endpoint,
                'p256dh'      => $sub['keys']['p256dh'] ?? null,
                'auth'        => $sub['keys']['auth'] ?? null,
                'ua'          => $ua,
            ]
        );
    }
}
