<?php

namespace Modules\PortalApi\Entities;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\Request;

class PortalOwnerDevice extends Model
{
    protected $table = 'portal_owner_devices';

    protected $fillable = [
        'owner_id', 'device_hash', 'platform', 'user_agent',
        'first_seen_at', 'last_seen_at', 'installed_at',
    ];

    protected $casts = [
        'first_seen_at' => 'datetime',
        'last_seen_at'  => 'datetime',
        'installed_at'  => 'datetime',
    ];

    /** Derive a coarse platform label from a UA string. */
    public static function platformFromUserAgent(?string $ua): string
    {
        $ua = strtolower($ua ?? '');
        if (preg_match('/iphone|ipad|ipod/', $ua))   return 'ios';
        if (preg_match('/android/', $ua))            return 'android';
        if (preg_match('/windows|macintosh|linux/', $ua)) return 'desktop';
        return 'other';
    }

    /** Stable per-owner per-browser hash — UA is enough as the key (no IP). */
    public static function hashFor(int $ownerId, ?string $ua): string
    {
        return hash('sha256', $ownerId . ':' . ($ua ?? 'unknown'));
    }

    /** Upsert a "this device just opened the PWA" event. */
    public static function ping(int $ownerId, Request $request, bool $installed): self
    {
        $ua  = $request->userAgent();
        $now = now();

        $device = self::firstOrNew([
            'owner_id'    => $ownerId,
            'device_hash' => self::hashFor($ownerId, $ua),
        ]);

        if (! $device->exists) {
            $device->first_seen_at = $now;
            $device->platform      = self::platformFromUserAgent($ua);
            $device->user_agent    = $ua;
        }
        $device->last_seen_at = $now;
        if ($installed && ! $device->installed_at) {
            $device->installed_at = $now;
        }
        $device->save();

        return $device;
    }
}
