<?php

namespace App\Models\Disk;

use App\Models\Agency\Agency;
use App\Models\User;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;

class DiskFolder extends Model
{
    use HasFactory, SoftDeletes;

    /**
     * The table associated with the model.
     */
    protected $table = 'disk_folders';

    /**
     * The attributes that are mass assignable.
     */
    protected $fillable = [
        'name',
        'slug',
        'description',
        'parent_id',
        'path',
        'level',
        'sort_order',
        'agency_id',
        'folder_type',
        'settings',
        'color_code',
        'icon',
        'item_count',
        'total_size_bytes',
        'is_active',
        'is_public',
        'permissions',
        'created_by',
        'updated_by',
    ];

    /**
     * The attributes that should be cast.
     */
    protected function casts(): array
    {
        return [
            'settings' => 'array',
            'permissions' => 'array',
            'item_count' => 'integer',
            'total_size_bytes' => 'integer',
            'level' => 'integer',
            'sort_order' => 'integer',
            'is_active' => 'boolean',
            'is_public' => 'boolean',
            'created_at' => 'datetime',
            'updated_at' => 'datetime',
            'deleted_at' => 'datetime',
        ];
    }

    /**
     * Get the agency that owns this folder.
     */
    public function agency(): BelongsTo
    {
        return $this->belongsTo(Agency::class);
    }

    /**
     * Get the parent folder.
     */
    public function parent(): BelongsTo
    {
        return $this->belongsTo(DiskFolder::class, 'parent_id');
    }

    /**
     * Get all child folders.
     */
    public function children(): HasMany
    {
        return $this->hasMany(DiskFolder::class, 'parent_id')
            ->orderBy('sort_order')
            ->orderBy('name');
    }

    /**
     * Get all items in this folder.
     */
    public function items(): HasMany
    {
        return $this->hasMany(DiskItem::class, 'folder_id')
            ->orderBy('sort_order')
            ->orderBy('original_name');
    }

    /**
     * Get the user who created this folder.
     */
    public function creator(): BelongsTo
    {
        return $this->belongsTo(User::class, 'created_by');
    }

    /**
     * Get the user who last updated this folder.
     */
    public function updater(): BelongsTo
    {
        return $this->belongsTo(User::class, 'updated_by');
    }

    /**
     * Get the full path hierarchy as array.
     */
    public function getPathHierarchy(): array
    {
        $hierarchy = [];
        $current = $this;

        while ($current) {
            array_unshift($hierarchy, [
                'id' => $current->id,
                'name' => $current->name,
                'slug' => $current->slug,
            ]);
            $current = $current->parent;
        }

        return $hierarchy;
    }

    /**
     * Get formatted size (human readable).
     */
    public function getFormattedSizeAttribute(): string
    {
        $bytes = $this->total_size_bytes;
        $units = ['B', 'KB', 'MB', 'GB', 'TB'];

        for ($i = 0; $bytes > 1024 && $i < count($units) - 1; $i++) {
            $bytes /= 1024;
        }

        return round($bytes, 2) . ' ' . $units[$i];
    }

    /**
     * Check if folder has children.
     */
    public function hasChildren(): bool
    {
        return $this->children()->count() > 0;
    }

    /**
     * Check if folder has items.
     */
    public function hasItems(): bool
    {
        return $this->items()->count() > 0;
    }

    /**
     * Check if folder is empty (no children and no items).
     */
    public function isEmpty(): bool
    {
        return !$this->hasChildren() && !$this->hasItems();
    }

    /**
     * Check if user can access this folder.
     */
    public function canAccess(User $user): bool
    {
        // Super admin can access all
        if ($user->isSuperAdmin()) {
            return true;
        }

        // Check agency
        if ($this->agency_id !== $user->agency_id) {
            return false;
        }

        // If public, allow access
        if ($this->is_public) {
            return true;
        }

        // Check permissions
        if ($this->permissions) {
            $userPermissions = $this->permissions['users'] ?? [];
            return in_array($user->id, $userPermissions);
        }

        return false;
    }

    /**
     * Scope to filter active folders.
     */
    public function scopeActive($query)
    {
        return $query->where('is_active', true);
    }

    /**
     * Scope to filter public folders.
     */
    public function scopePublic($query)
    {
        return $query->where('is_public', true);
    }

    /**
     * Scope to filter by agency.
     */
    public function scopeByAgency($query, $agencyId)
    {
        return $query->where('agency_id', $agencyId);
    }

    /**
     * Scope to filter root folders (no parent).
     */
    public function scopeRoot($query)
    {
        return $query->whereNull('parent_id');
    }

    /**
     * Scope to filter by folder type.
     */
    public function scopeByType($query, $type)
    {
        return $query->where('folder_type', $type);
    }

    /**
     * Scope to filter by level.
     */
    public function scopeByLevel($query, $level)
    {
        return $query->where('level', $level);
    }

    /**
     * Update item count and total size.
     */
    public function updateStatistics(): void
    {
        $this->item_count = $this->items()->count();
        $this->total_size_bytes = $this->items()->sum('file_size');
        $this->save();

        // Update parent statistics recursively
        if ($this->parent) {
            $this->parent->updateStatistics();
        }
    }

    /**
     * Boot the model.
     */
    protected static function boot()
    {
        parent::boot();

        static::creating(function ($folder) {
            if (auth()->check()) {
                $folder->created_by = auth()->id();
            }

            // Auto-generate slug if not provided
            if (empty($folder->slug)) {
                $folder->slug = \Illuminate\Support\Str::slug($folder->name);
            }

            // Calculate level and path based on parent
            if ($folder->parent_id) {
                $parent = self::find($folder->parent_id);
                if ($parent) {
                    $folder->level = $parent->level + 1;
                    $folder->path = $parent->path ? $parent->path . '/' . $folder->slug : $folder->slug;
                }
            } else {
                $folder->level = 0;
                $folder->path = $folder->slug;
            }
        });

        static::updating(function ($folder) {
            if (auth()->check()) {
                $folder->updated_by = auth()->id();
            }

            // Update slug if name changed
            if ($folder->isDirty('name') && empty($folder->slug)) {
                $folder->slug = \Illuminate\Support\Str::slug($folder->name);
            }

            // Update path if parent or slug changed
            if ($folder->isDirty(['parent_id', 'slug'])) {
                if ($folder->parent_id) {
                    $parent = self::find($folder->parent_id);
                    if ($parent) {
                        $folder->level = $parent->level + 1;
                        $folder->path = $parent->path ? $parent->path . '/' . $folder->slug : $folder->slug;
                    }
                } else {
                    $folder->level = 0;
                    $folder->path = $folder->slug;
                }

                // Update children paths recursively
                self::updateChildrenPaths($folder);
            }
        });

        static::deleting(function ($folder) {
            // Delete all items in this folder
            $folder->items()->delete();

            // Delete all child folders recursively
            foreach ($folder->children as $child) {
                $child->delete();
            }
        });
    }

    /**
     * Update paths for all children recursively.
     */
    protected static function updateChildrenPaths(DiskFolder $folder): void
    {
        foreach ($folder->children as $child) {
            $child->level = $folder->level + 1;
            $child->path = $folder->path ? $folder->path . '/' . $child->slug : $child->slug;
            $child->save();

            self::updateChildrenPaths($child);
        }
    }
}
