<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Support\Facades\Storage;

class RawMaterialFile extends Model
{
    use HasFactory, SoftDeletes;

    protected $table = 'raw_material_files';

    protected $fillable = [
        'raw_material_id',
        'file_path',
        'file_name',
        'file_type',
        'file_size',
    ];

    protected $casts = [
        'file_size' => 'integer',
        'created_at' => 'datetime',
        'updated_at' => 'datetime',
    ];

    // ──────────────────────────────────────────────────────────────────────────
    // RELATIONSHIPS
    // ──────────────────────────────────────────────────────────────────────────

    /**
     * Get the raw material this file belongs to
     */
    public function rawMaterial()
    {
        return $this->belongsTo(RawMaterial::class);
    }

    // ──────────────────────────────────────────────────────────────────────────
    // ACCESSORS
    // ──────────────────────────────────────────────────────────────────────────

    /**
     * Get the full URL to the file
     */
    public function getUrlAttribute(): string
    {
        return Storage::disk('public')->url($this->file_path);
    }

    /**
     * Get human-readable file size
     */
    public function getHumanSizeAttribute(): string
    {
        $bytes = $this->file_size ?? 0;
        $units = ['B', 'KB', 'MB', 'GB'];
        $i = 0;
        while ($bytes >= 1024 && $i < count($units) - 1) {
            $bytes /= 1024;
            $i++;
        }
        return round($bytes, 2) . ' ' . $units[$i];
    }

    /**
     * Get file extension
     */
    public function getExtensionAttribute(): string
    {
        return pathinfo($this->file_name, PATHINFO_EXTENSION);
    }

    // ──────────────────────────────────────────────────────────────────────────
    // HELPERS
    // ──────────────────────────────────────────────────────────────────────────

    /**
     * Check if file is an image
     */
    public function isImage(): bool
    {
        return in_array(strtolower($this->extension), ['jpg', 'jpeg', 'png', 'gif', 'webp']);
    }

    /**
     * Check if file is a document
     */
    public function isDocument(): bool
    {
        return in_array(strtolower($this->extension), ['pdf', 'doc', 'docx', 'xls', 'xlsx']);
    }

    /**
     * Delete the physical file when model is deleted
     */
    protected static function booted(): void
    {
        static::deleting(function (RawMaterialFile $file) {
            if (!$file->isForceDeleting()) {
                return; // Don't delete file on soft delete
            }
            Storage::disk('public')->delete($file->file_path);
        });
    }
}
