<?php

namespace App\Models\Messenger;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Support\Facades\Storage;

class MessageAttachment extends Model
{
    protected $fillable = [
        'message_id',
        'type',
        'file_name',
        'file_path',
        'mime_type',
        'file_size',
        'metadata',
        'thumbnail_path',
        'storage_driver',
    ];

    protected $casts = [
        'file_size' => 'integer',
        'metadata' => 'array',
    ];

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

    public function getUrlAttribute(): string
    {
        return getMedia($this->file_path, $this->type, $this->storage_driver);
    }

    public function getThumbnailUrlAttribute(): ?string
    {
        if (!$this->thumbnail_path) {
            return null;
        }

        return getMedia($this->thumbnail_path, 'thumbnail', $this->storage_driver);
    }

    public function getFormattedSizeAttribute(): string
    {
        return humanFilesize($this->file_size);
    }

    public function isImage(): bool
    {
        return $this->type === 'image';
    }

    public function isVideo(): bool
    {
        return $this->type === 'video';
    }

    public function isAudio(): bool
    {
        return $this->type === 'audio';
    }

    public function isDocument(): bool
    {
        return $this->type === 'document';
    }

    public function delete(): bool
    {
        // Delete physical files
        if ($this->file_path) {
            Storage::disk($this->storage_driver)->delete($this->file_path);
        }
        
        if ($this->thumbnail_path) {
            Storage::disk($this->storage_driver)->delete($this->thumbnail_path);
        }

        return parent::delete();
    }
}
