<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Support\Str;

class PhotoShareLink extends Model
{
    use HasFactory;

    protected $fillable = [
        'photo_id',
        'slug',
        'expires_at',
        'created_by_device_id',
        'created_ip',
        'last_accessed_at',
    ];

    protected $casts = [
        'expires_at' => 'datetime',
        'last_accessed_at' => 'datetime',
    ];

    protected static function booted(): void
    {
        static::creating(function (PhotoShareLink $link) {
            if (! $link->slug) {
                $link->slug = static::generateSlug();
            }
        });
    }

    public static function generateSlug(): string
    {
        return Str::lower(Str::random(40));
    }

    public function photo(): BelongsTo
    {
        return $this->belongsTo(Photo::class);
    }

    public function isExpired(): bool
    {
        return $this->expires_at !== null && $this->expires_at->isPast();
    }
}
