<?php

namespace App\Models;

use App\Events\DocumentVersionUpdated;
use Illuminate\Database\Eloquent\Model;
use Spatie\Activitylog\LogOptions;
use Spatie\Activitylog\Traits\LogsActivity;

class Document extends Model
{

    use LogsActivity;
    
    protected static $logAttributes = ['name', 'status'];
    protected static $logOnlyDirty = true;

    protected $fillable = [
        'name',
        'file_path',
        'project_id', // Asegurar que está en fillable
        'folder_id',
        'user_id',
        'status'
    ];


    public function versions() {
        return $this->hasMany(DocumentVersion::class);
    }
    
    public function approvals() {
        return $this->hasMany(Approval::class);
    }
    
    public function comments() {
        return $this->hasMany(Comment::class)->whereNull('parent_id');
    }


    public function createVersion($file)
    {
        return $this->versions()->create([
            'file_path' => $file->store("documents/{$this->id}/versions"),
            'hash' => hash_file('sha256', $file),
            'user_id' => auth()->id(),
            'version_number' => $this->versions()->count() + 1
        ]);
    }
    
    public function getCurrentVersionAttribute()
    {
        return $this->versions()->latest()->first();
    }

    public function uploadVersion($file)
    {
        $this->versions()->create([
            'file_path' => $file->store("projects/{$this->id}/versions"),
            'hash' => hash_file('sha256', $file),
            'version' => $this->versions()->count() + 1,
            'user_id' => auth()->id()
        ]);
        
        event(new DocumentVersionUpdated($this));

        return $version;
    }

    public function getActivitylogOptions(): LogOptions
    {
        return LogOptions::defaults()
            ->logExcept(['current_version_id'])
            ->logUnguarded();
    }

}
