<?php

namespace App\Models;

use App\Models\Concerns\BelongsToOwner;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Support\Str;

class SessionFile extends Model
{
    use BelongsToOwner;

    protected $table = 'meet_session_files';

    protected $fillable = [
        'uuid', 'owner_ref', 'room_id', 'session_id', 'uploaded_by_ref', 'uploaded_by_name',
        'original_name', 'storage_path', 'mime_type', 'file_size', 'drive_file_id', 'expires_at',
        'storage_paid_until', 'storage_grace_ends_at', 'storage_last_billed_at',
    ];

    protected function casts(): array
    {
        return [
            'expires_at' => 'datetime',
            'storage_paid_until' => 'datetime',
            'storage_grace_ends_at' => 'datetime',
            'storage_last_billed_at' => 'datetime',
        ];
    }

    protected static function booted(): void
    {
        static::creating(function (SessionFile $file) {
            if (empty($file->uuid)) {
                $file->uuid = (string) Str::uuid();
            }
        });
    }

    public function getRouteKeyName(): string
    {
        return 'uuid';
    }

    public function room(): BelongsTo
    {
        return $this->belongsTo(Room::class, 'room_id');
    }

    public function session(): BelongsTo
    {
        return $this->belongsTo(Session::class, 'session_id');
    }

    public function downloads(): HasMany
    {
        return $this->hasMany(FileDownload::class, 'session_file_id');
    }

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