<?php

namespace App\Models;

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

class CommunityPostImage extends Model
{
    protected $fillable = [
        'community_post_id',
        'image_path',
        'original_name',
        'file_size',
    ];

    protected function casts(): array
    {
        return [
            'file_size' => 'integer',
        ];
    }

    protected static function booted(): void
    {
        static::deleting(function (CommunityPostImage $image): void {
            if (filled($image->image_path)) {
                Storage::disk('public')->delete($image->image_path);
            }
        });
    }

    public function post(): BelongsTo
    {
        return $this->belongsTo(CommunityPost::class, 'community_post_id');
    }

    public function imageUrl(): string
    {
        return asset('storage/'.$this->image_path);
    }

    public function formattedSize(): string
    {
        if ($this->file_size >= 1048576) {
            return round($this->file_size / 1048576, 1).' MB';
        }

        return max(1, round($this->file_size / 1024)).' KB';
    }
}
