<?php

namespace App\Models;

use App\Models\SpaceUpdate;
use App\Services\WebPushService;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

class Activity extends Model
{
    public $timestamps = false;
    public $incrementing = false;
    protected $keyType = 'string';

    protected $fillable = [
        'id',
        'space_id',
        'activity_type',
        'description',
        'i18n',
        'user_person_id',
        'amount',
        'group_name',
        'list_name',
        'activity_at',
    ];

    protected $casts = [
        'i18n' => 'array',
        'amount' => 'float',
        'activity_at' => 'datetime',
    ];

    public function user(): BelongsTo
    {
        return $this->belongsTo(Person::class, 'user_person_id', 'id');
    }

    protected static function booted(): void
    {
        static::created(function (Activity $activity) {
            $spaceId = (string) $activity->space_id;
            if ($spaceId !== '') {
                SpaceUpdate::bump($spaceId);
            }

            // Best-effort Web Push (no queues required).
            try {
                $actorUserId = Person::query()->where('id', (string) $activity->user_person_id)->value('auth_user_id');
                $title = 'WeShare';
                $body = (string) ($activity->group_name ?: $activity->list_name ?: $activity->description ?: 'Update');
                app(WebPushService::class)->sendToSpace($spaceId, [
                    'title' => $title,
                    'body' => $body,
                    'url' => '/',
                ], $actorUserId ? (int) $actorUserId : null);
            } catch (\Throwable $e) {
                // Non-fatal.
            }
        });
    }
}

