<?php

namespace App\Models;

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

class TaskFile extends BaseModel
{
    use HasFactory;

    protected $fillable = [
        'task_id',
        'name',
        'file_path',
        'file_type',
        'file_size',
        'created_by',
    ];

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

    protected $appends = [
        'file_size_formatted'
    ];

    public function task()
    {
        return $this->belongsTo(Task::class);
    }

    public function creator()
    {
        return $this->belongsTo(User::class, 'created_by');
    }

    public function getFileSizeFormattedAttribute()
    {
        if (!$this->file_size) {
            // Try to get file size if not stored
            if ($this->file_path) {
                $fullPath = public_path($this->file_path);
                if (file_exists($fullPath)) {
                    $bytes = filesize($fullPath);
                    $this->update(['file_size' => $bytes]);
                } else {
                    return 'Unknown';
                }
            } else {
                return 'Unknown';
            }
        } else {
            $bytes = $this->file_size;
        }
        
        $units = ['B', 'KB', 'MB', 'GB'];
        
        for ($i = 0; $bytes > 1024 && $i < count($units) - 1; $i++) {
            $bytes /= 1024;
        }
        
        return round($bytes, 2) . ' ' . $units[$i];
    }

    protected static function boot()
    {
        parent::boot();
        
        static::deleting(function ($taskFile) {
            if (Storage::disk('public')->exists($taskFile->file_path)) {
                Storage::disk('public')->delete($taskFile->file_path);
            }
        });
    }
}